// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/ClientSurveyForEventOrder/Page.jsx

import React, { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router";
import {
  ClipboardDocumentListIcon,
  HomeIcon,
  ExclamationTriangleIcon,
  ChatBubbleLeftRightIcon,
} from "@heroicons/react/24/outline";
import {
  Breadcrumb,
  Button,
  Card,
  Alert,
  LoadingSpinner,
  useUIXTheme,
  UIXThemeProvider,
  RadioGroup,
  Select,
  Textarea,
} from "../../../../components/UIX";
import {
  useTaskManager,
} from "../../../../services/Services";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";
import { TASK_NO_SURVEY_CONDUCTED_REASON_OPTIONS } from "../../../../constants/Task";

function AdminTaskItemClientSurveyForEventOrderPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const taskManager = useTaskManager();
  const { getThemeClasses } = useUIXTheme();

  // State
  const [taskItem, setTaskItem] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState({});
  const errorRef = useRef(null);

  // Form state
  const [surveyConducted, setSurveyConducted] = useState("");
  const [facilitatorsPunctual, setFacilitatorsPunctual] = useState("");
  const [facilitatorsProfessional, setFacilitatorsProfessional] = useState("");
  const [studentsEngaged, setStudentsEngaged] = useState("");
  const [materialRelevant, setMaterialRelevant] = useState("");
  const [wouldConsiderAgain, setWouldConsiderAgain] = useState("");
  const [noSurveyReason, setNoSurveyReason] = useState(0); // Initialize as number
  const [comments, setComments] = useState("");

  // Scroll to error only when new errors appear (not when clearing)
  const prevErrorCountRef = useRef(0);
  useEffect(() => {
    const currentErrorCount = Object.keys(errors).length;

    // Only scroll if error count INCREASED (new errors), not decreased (cleared errors)
    if (currentErrorCount > prevErrorCountRef.current && currentErrorCount > 0 && errorRef.current) {
      errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    }

    prevErrorCountRef.current = currentErrorCount;
  }, [errors]);

  // Clear specific field error when user starts typing
  const clearFieldError = (fieldName) => {
    if (errors[fieldName]) {
      setErrors((prevErrors) => {
        const newErrors = { ...prevErrors };
        delete newErrors[fieldName];
        return newErrors;
      });
    }
  };

  // Load task item details
  useEffect(() => {
    if (id) {
      loadTaskItem();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const loadTaskItem = async () => {
    try {
      setIsLoading(true);
      setErrors({});

      const onUnauthorized = () => navigate("/login?unauthorized=true");

      // Fetch the task item (contains all event order data)
      const taskResponse = await taskManager.getTaskDetail(id, onUnauthorized);
      setTaskItem(taskResponse);

      if (import.meta.env.DEV) {
        console.log("ClientSurveyForEventOrder: Task item loaded:", taskResponse);
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading task item:", error);
      }
      setErrors({
        general: "Failed to load task item. Please try again.",
      });
    } finally {
      setIsLoading(false);
    }
  };

  // Helper functions to calculate seat values
  const getEstimatedSeats = () => {
    if (!taskItem) return 0;
    const seats = taskItem.eventOrderEstimatedNumberOfAttendees;
    if (seats === undefined || seats === null) return 0;
    return typeof seats === "number" ? seats : parseInt(seats) || 0;
  };

  const getActualSeats = () => {
    if (!taskItem) return 0;
    const seats = taskItem.eventOrderActualNumberOfAttendees;
    if (seats === undefined || seats === null) return 0;
    return typeof seats === "number" ? seats : parseInt(seats) || 0;
  };

  const getVarianceSeats = () => {
    if (!taskItem) return 0;
    const variance = taskItem.eventOrderVarianceOfNumberOfAttendees;
    if (variance === undefined || variance === null) {
      return getActualSeats() - getEstimatedSeats();
    }
    return typeof variance === "number" ? variance : parseFloat(variance) || 0;
  };

  // Handle form submission
  const handleSubmitSurvey = async () => {
    try {
      setIsSubmitting(true);
      setErrors({});

      // Build survey data object - only include taskItemId initially
      const surveyData = {
        taskItemId: taskItem.id,
      };

      // Only include surveyConducted if user has selected yes or no
      if (surveyConducted === "yes" || surveyConducted === "no") {
        surveyData.surveyConducted = surveyConducted === "yes";
      }

      // Only include survey responses if survey was conducted AND user answered them
      if (surveyConducted === "yes") {
        if (facilitatorsPunctual) {
          surveyData.facilitatorsPunctual = facilitatorsPunctual === "yes";
        }
        if (facilitatorsProfessional) {
          surveyData.facilitatorsProfessional = facilitatorsProfessional === "yes";
        }
        if (studentsEngaged) {
          surveyData.studentsEngaged = studentsEngaged === "yes";
        }
        if (materialRelevant) {
          surveyData.materialRelevant = materialRelevant === "yes";
        }
        if (wouldConsiderAgain) {
          surveyData.wouldConsiderAgain = wouldConsiderAgain === "yes";
        }
      }

      // Debug logging
      if (import.meta.env.DEV) {
        console.log("ClientSurvey: surveyConducted =", surveyConducted);
      }
      if (import.meta.env.DEV) {
        console.log("ClientSurvey: noSurveyReason state =", noSurveyReason);
      }
      if (import.meta.env.DEV) {
        console.log("ClientSurvey: noSurveyReason type =", typeof noSurveyReason);
      }

      // Only include noSurveyReason if survey was not conducted AND user selected a valid reason
      if (surveyConducted === "no" && noSurveyReason > 0) {
        // noSurveyReason is already an integer from the onChange handler
        surveyData.noSurveyReason = noSurveyReason;
        if (import.meta.env.DEV) {
          console.log("ClientSurvey: Added noSurveyReason to surveyData:", noSurveyReason);
        }
      } else {
        if (import.meta.env.DEV) {
          console.log("ClientSurvey: NOT adding noSurveyReason. surveyConducted:", surveyConducted, "noSurveyReason:", noSurveyReason);
        }
      }

      // Only include comments if they're not empty
      if (comments.trim()) {
        surveyData.comments = comments.trim();
      }

      if (import.meta.env.DEV) {
        console.log("ClientSurvey: Final survey data:", surveyData);
      }

      const onUnauthorized = () => navigate("/login?unauthorized=true");
      await taskManager.surveyEventOrder(surveyData, onUnauthorized);

      if (import.meta.env.DEV) {
        console.log("ClientSurvey: Survey submitted successfully");
      }
      navigate("/admin/tasks?success=survey_submitted");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("ClientSurvey: Error submitting survey:", error);
      }

      // Handle validation errors from backend
      if (error && typeof error === "object" && !error.message) {
        // Backend returned field-specific validation errors
        setErrors(error);

        // Scroll to the first error field
        if (errorRef.current) {
          errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      } else {
        // General error (network, server error, etc.)
        const errorMessage = error.message || error.toString() || "Failed to submit survey. Please try again.";
        setErrors({
          general: errorMessage,
        });
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Breadcrumb items
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Task Items",
      to: "/admin/tasks",
      icon: ClipboardDocumentListIcon,
    },
    {
      label: "Client Survey for Event Order",
      icon: ChatBubbleLeftRightIcon,
      isActive: true,
    },
  ];

  if (isLoading) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen flex items-center justify-center">
          <LoadingSpinner size="lg" />
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className={`min-h-screen ${getThemeClasses("bg-primary")}`}>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          {/* Breadcrumb */}
          <Breadcrumb items={breadcrumbItems} />

          {/* Header */}
          <div className="mt-6 mb-8">
            <h1
              className={`text-3xl font-bold ${getThemeClasses("text-primary")}`}
            >
              Client Survey for Event Order
            </h1>
            <p className={`mt-2 ${getThemeClasses("text-secondary")}`}>
              Collect survey feedback from client for event order
            </p>
          </div>

          {/* Error Alerts */}
          {errors.general && (
            <div ref={errorRef} className="mb-6">
              <Alert variant="error">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
                  </div>
                  <div className="ml-3 flex-1">
                    <h3 className="text-sm font-medium text-red-800">
                      Operation Failed
                    </h3>
                    <div className="mt-2 text-sm text-red-700">
                      <p className="whitespace-pre-wrap">{errors.general}</p>
                    </div>
                  </div>
                </div>
              </Alert>
            </div>
          )}

          {/* Validation Errors Summary */}
          {!errors.general && Object.keys(errors).length > 0 && (
            <div ref={errorRef} className="mb-6">
              <Alert variant="error">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
                  </div>
                  <div className="ml-3 flex-1">
                    <h3 className="text-sm font-medium text-red-800">
                      Please correct the following errors:
                    </h3>
                    <div className="mt-2 text-sm text-red-700">
                      <ul className="list-disc list-inside space-y-1">
                        {Object.entries(errors).map(([field, message]) => (
                          <li key={field}>
                            <strong className="capitalize">
                              {field.replace(/([A-Z])/g, ' $1').trim()}:
                            </strong>{' '}
                            {message}
                          </li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              </Alert>
            </div>
          )}

          {/* Task Item Details */}
          {taskItem && (
            <>
              {/* Main Event Order Information Card */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Event Order Information
                  </h2>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Event Title */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Event Title
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventName || "-"}
                      </p>
                    </div>

                    {/* Event Date */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Event Date
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.eventEndDateTime
                          ? formatDateForDisplay(taskItem.eventEndDateTime)
                          : "-"}
                      </p>
                    </div>

                    {/* Organization Short Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Organization Short Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.customerOrganizationShortName || "-"}
                      </p>
                    </div>

                    {/* Division Short Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Division Short Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.customerDivisionShortName || "-"}
                      </p>
                    </div>

                    {/* Customer Name */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Customer Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.customerName || "-"}
                      </p>
                    </div>

                    {/* Customer Phone */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Customer Phone
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.customerPhone || "-"}
                      </p>
                    </div>

                    {/* Customer Email */}
                    <div>
                      <label
                        className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}
                      >
                        Customer Email
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text-primary")}`}
                      >
                        {taskItem.customerEmail || "-"}
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Event Order Seat Information Card */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Seat Information
                  </h2>

                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    {/* Estimated Seats */}
                    <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                      <label className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}>
                        Estimated Seats
                      </label>
                      <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                        {getEstimatedSeats()}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Seats ordered during event order creation
                      </p>
                    </div>

                    {/* Actual Seats Ordered */}
                    <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                      <label className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}>
                        Actual Seats Ordered
                      </label>
                      <p className={`text-2xl font-bold ${getThemeClasses("text-primary")}`}>
                        {getActualSeats()}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        From Event Order Review task
                      </p>
                    </div>

                    {/* Variance */}
                    <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}>
                      <label className={`block text-sm font-medium mb-1 ${getThemeClasses("text-secondary")}`}>
                        Variance
                      </label>
                      <p
                        className={`text-2xl font-bold ${
                          getVarianceSeats() >= 0
                            ? "text-green-600"
                            : "text-red-600"
                        }`}
                      >
                        {getVarianceSeats() >= 0 ? "+" : ""}
                        {getVarianceSeats()}
                      </p>
                      <p className={`text-xs ${getThemeClasses("text-muted")} mt-1`}>
                        Actual - Estimated
                      </p>
                    </div>
                  </div>
                </div>
              </Card>

              {/* Client Survey Form Card */}
              <Card className="mb-6">
                <div className="p-6">
                  <h2
                    className={`text-xl font-semibold mb-6 ${getThemeClasses("text-primary")}`}
                  >
                    Client Survey
                  </h2>

                  <div className="space-y-6">
                    {/* Was Survey Conducted? */}
                    <div>
                      <RadioGroup
                        name="survey-conducted"
                        label="Was a client survey conducted?"
                        value={surveyConducted}
                        onChange={(value) => {
                          setSurveyConducted(value);
                          clearFieldError("surveyConducted");
                        }}
                        options={[
                          { value: "yes", label: "Yes" },
                          { value: "no", label: "No" },
                        ]}
                        required={true}
                        error={errors.surveyConducted}
                      />
                    </div>

                    {/* If YES - Show 5 Questions */}
                    {surveyConducted === "yes" && (
                      <div className="space-y-6 pl-4 border-l-4 border-blue-200">
                        <div>
                          <RadioGroup
                            name="facilitators-punctual"
                            label="Were the facilitators and speakers punctual?"
                            value={facilitatorsPunctual}
                            onChange={(value) => {
                              setFacilitatorsPunctual(value);
                              clearFieldError("facilitatorsPunctual");
                            }}
                            options={[
                              { value: "yes", label: "Yes" },
                              { value: "no", label: "No" },
                            ]}
                            required={true}
                            error={errors.facilitatorsPunctual}
                          />
                        </div>

                        <div>
                          <RadioGroup
                            name="facilitators-professional"
                            label="Were the facilitators and speakers professional?"
                            value={facilitatorsProfessional}
                            onChange={(value) => {
                              setFacilitatorsProfessional(value);
                              clearFieldError("facilitatorsProfessional");
                            }}
                            options={[
                              { value: "yes", label: "Yes" },
                              { value: "no", label: "No" },
                            ]}
                            required={true}
                            error={errors.facilitatorsProfessional}
                          />
                        </div>

                        <div>
                          <RadioGroup
                            name="students-engaged"
                            label="Were the students engaged?"
                            value={studentsEngaged}
                            onChange={(value) => {
                              setStudentsEngaged(value);
                              clearFieldError("studentsEngaged");
                            }}
                            options={[
                              { value: "yes", label: "Yes" },
                              { value: "no", label: "No" },
                            ]}
                            required={true}
                            error={errors.studentsEngaged}
                          />
                        </div>

                        <div>
                          <RadioGroup
                            name="material-relevant"
                            label="Was the material relevant and easy to understand?"
                            value={materialRelevant}
                            onChange={(value) => {
                              setMaterialRelevant(value);
                              clearFieldError("materialRelevant");
                            }}
                            options={[
                              { value: "yes", label: "Yes" },
                              { value: "no", label: "No" },
                            ]}
                            required={true}
                            error={errors.materialRelevant}
                          />
                        </div>

                        <div>
                          <RadioGroup
                            name="would-consider-again"
                            label="Would you consider Flashpoint again in the future?"
                            value={wouldConsiderAgain}
                            onChange={(value) => {
                              setWouldConsiderAgain(value);
                              clearFieldError("wouldConsiderAgain");
                            }}
                            options={[
                              { value: "yes", label: "Yes" },
                              { value: "no", label: "No" },
                            ]}
                            required={true}
                            error={errors.wouldConsiderAgain}
                          />
                        </div>
                      </div>
                    )}

                    {/* If NO - Show Reason Dropdown */}
                    {surveyConducted === "no" && (
                      <div className="pl-4 border-l-4 border-red-200">
                        <Select
                          label="Reason for not conducting survey"
                          value={noSurveyReason}
                          onChange={(value) => {
                            // Convert to integer immediately when user selects
                            setNoSurveyReason(parseInt(value, 10));
                            clearFieldError("noSurveyReason");
                          }}
                          options={TASK_NO_SURVEY_CONDUCTED_REASON_OPTIONS}
                          required={true}
                          error={errors.noSurveyReason}
                        />
                      </div>
                    )}

                    {/* Comments (Optional) */}
                    <div>
                      <Textarea
                        label="Comments (Optional)"
                        placeholder="Enter any additional comments about the survey..."
                        value={comments}
                        onChange={(value) => {
                          setComments(value);
                          clearFieldError("comments");
                        }}
                        rows={4}
                        error={errors.comments}
                      />
                    </div>
                  </div>
                </div>
              </Card>

              {/* Action Buttons */}
              <div className="flex justify-end gap-3">
                <Button
                  variant="secondary"
                  onClick={() => navigate("/admin/tasks")}
                  disabled={isSubmitting}
                >
                  Back to Task Items
                </Button>
                <Button
                  variant="primary"
                  onClick={handleSubmitSurvey}
                  disabled={isSubmitting}
                  loading={isSubmitting}
                >
                  {isSubmitting ? "Submitting..." : "Submit Survey"}
                </Button>
              </div>
            </>
          )}

          {/* No Task Item Found */}
          {!isLoading && !taskItem && (
            <Card>
              <div className="p-6">
                <Alert variant="warning" className="mb-6">
                  <ExclamationTriangleIcon className="w-5 h-5" />
                  <span>No task item details available.</span>
                </Alert>

                <div className="flex justify-end">
                  <Button
                    variant="secondary"
                    onClick={() => navigate("/admin/tasks")}
                  >
                    Back to Task Items
                  </Button>
                </div>
              </div>
            </Card>
          )}
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemClientSurveyForEventOrderPage;
