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

import React, { useState, useEffect, useRef } from "react";
import { useParams, useNavigate } from "react-router";
import {
  ClipboardDocumentListIcon,
  HomeIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon,
  TagIcon,
  AcademicCapIcon,
  CpuChipIcon,
  ShieldCheckIcon,
  FolderIcon,
  LockClosedIcon,
} from "@heroicons/react/24/outline";
import {
  Breadcrumb,
  Button,
  RadioGroup,
  Select,
  TextArea,
  Card,
  Alert,
  LoadingSpinner,
  useUIXTheme,
  UIXThemeProvider,
} from "../../../../components/UIX";
import {
  TASK_ITEM_CLOSE_EVENT_AS_PLANNED,
  TASK_ITEM_CLOSE_REASON,
  TASK_ITEM_CLOSE_REASON_OPTIONS,
  TASK_ITEM_STATUS,
} from "../../../../constants/Task";
import { useTaskManager } from "../../../../services/Services";

// Helper component to display badge list
const BadgeList = ({ items, icon: Icon, label }) => {
  const { getThemeClasses } = useUIXTheme();

  if (!items || items.length === 0) return null;

  const getBadgeText = (item) => {
    // For skill sets, combine category and subcategory if available
    if (item.category) {
      return item.subCategory
        ? `${item.category} - ${item.subCategory}`
        : item.category;
    }
    // For other items, use name or text
    return item.name || item.text || "N/A";
  };

  return (
    <div className="mb-4">
      <label className={`block text-sm font-medium ${getThemeClasses("text-secondary")} mb-2`}>
        {label}
      </label>
      <div className="flex flex-wrap gap-2">
        {items.map((item, index) => (
          <span
            key={item.id || index}
            className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200"
            title={item.description || ""}
          >
            {getBadgeText(item)}
          </span>
        ))}
      </div>
    </div>
  );
};

function AdminTaskItemCloseEventContractPage() {
  const { tid } = 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 [successMessage, setSuccessMessage] = useState("");
  const errorRef = useRef(null);

  // Form state
  const [eventAsPlanned, setEventAsPlanned] = useState("");
  const [closingReason, setClosingReason] = useState("");
  const [closingReasonOther, setClosingReasonOther] = useState("");
  const [additionalComment, setAdditionalComment] = useState("");

  // Load task item details
  useEffect(() => {
    if (tid) {
      loadTaskItem();
    }
  }, [tid]);

  // Scroll to error when it appears
  useEffect(() => {
    if (errors.general && errorRef.current) {
      errorRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    }
  }, [errors.general]);

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

      const response = await taskManager.getTaskDetail(tid, () =>
        navigate("/login?unauthorized=true"),
      );

      setTaskItem(response);
    } 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);
    }
  };

  // Handle event as planned change
  const handleEventAsPlannedChange = (value) => {
    setEventAsPlanned(value);
    setErrors({});

    if (value === TASK_ITEM_CLOSE_EVENT_AS_PLANNED.YES.toString()) {
      // Clear closing reason since it's not needed for YES
      setClosingReason("");
      setClosingReasonOther("");
    } else if (value === TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString()) {
      // Clear closing reason for NO responses
      setClosingReason("");
      setClosingReasonOther("");
    }
  };

  // Handle closing reason change
  const handleClosingReasonChange = (value) => {
    setClosingReason(value);
    setErrors({});

    // Clear other reason field if not "Other"
    if (parseInt(value) !== TASK_ITEM_CLOSE_REASON.CANCELLED_BY_OTHER) {
      setClosingReasonOther("");
    }
  };

  // Handle form submission
  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      setIsSubmitting(true);
      setErrors({});

      // Validate form
      const validationErrors = validateForm();
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }

      // Prepare close data
      const closeData = {
        task_item_id: tid,
        did_this_event_take_place_as_planned: parseInt(eventAsPlanned),
      };

      // Add additional comment only if provided
      if (additionalComment.trim()) {
        closeData.additional_comment = additionalComment.trim();
      }

      // Add closing reason only if event did NOT take place as planned
      if (eventAsPlanned === TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString()) {
        closeData.closing_reason = parseInt(closingReason);

        // Add other reason if selected
        if (
          parseInt(closingReason) ===
            TASK_ITEM_CLOSE_REASON.CANCELLED_BY_OTHER &&
          closingReasonOther.trim()
        ) {
          closeData.closing_reason_other = closingReasonOther.trim();
        }
      } else {
        // For successful events, use "Successful" reason
        closeData.closing_reason = TASK_ITEM_CLOSE_REASON.SUCCESSFUL;
      }

      if (import.meta.env.DEV) {
        console.log("Submitting close event contract data:", closeData);
      }

      await taskManager.closeEventContract(closeData, () =>
        navigate("/login?unauthorized=true"),
      );

      // Redirect immediately with success message
      navigate("/admin/tasks", {
        state: {
          successMessage: "Event contract has been successfully closed.",
        },
      });
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error closing task item:", error);
      }

      // Helper function to format field names
      const formatFieldName = (fieldName) => {
        return fieldName
          .replace(/_/g, " ")
          .replace(/([A-Z])/g, " $1")
          .toLowerCase()
          .replace(/^./, (str) => str.toUpperCase());
      };

      // Enhanced error handling with field-specific messages
      if (typeof error === "object" && error !== null) {
        // Customer-related validation errors
        if (error.customerEmail) {
          setErrors({
            general: `Missing Customer Email\n\nThe customer does not have an email address on file, which is required.\n\nPlease update the customer's profile to add an email address.`,
          });
        } else if (error.customerPhone) {
          setErrors({
            general: `Missing Customer Phone\n\nThe customer does not have a phone number on file, which is required.\n\nPlease update the customer's profile to add a phone number.`,
          });
        } else if (error.customerName) {
          setErrors({
            general: `Missing Customer Name\n\nThe customer is missing required name information.\n\nPlease ensure the customer has complete profile information.`,
          });
        } else if (error.customerOrganizationName || error.customerOrganizationShortName) {
          setErrors({
            general: `Missing Organization Information\n\nThe customer's organization is missing required information.\n\nPlease contact your system administrator to update the organization details.`,
          });
        } else if (error.customerDivisionName || error.customerDivisionShortName) {
          setErrors({
            general: `Missing Division Information\n\nThe customer's division is missing required information.\n\nPlease contact your system administrator to update the division details.`,
          });
        }
        // Speaker/Facilitator validation errors
        else if (error.speakerEmail || error.facilitatorEmail) {
          setErrors({
            general: `Missing Contact Email\n\nThe selected speaker/facilitator does not have an email address on file, which is required.\n\nPlease update their profile to add an email address.`,
          });
        } else if (error.speakerPhone || error.facilitatorPhone) {
          setErrors({
            general: `Missing Contact Phone\n\nThe selected speaker/facilitator does not have a phone number on file, which is required.\n\nPlease update their profile to add a phone number.`,
          });
        }
        // Event-related validation errors
        else if (error.eventName || error.eventDescription) {
          setErrors({
            general: `Invalid Event Information\n\nThe event is missing required information.\n\nPlease contact your system administrator to update the event details.`,
          });
        } else if (error.eventCategoryName) {
          setErrors({
            general: `Missing Event Category\n\nThe event category information is missing or invalid.\n\nPlease contact your system administrator.`,
          });
        }
        // General error handling
        else if (error.message) {
          setErrors({
            general: `Error\n\n${error.message}\n\nPlease try again.`,
          });
        } else {
          // Display all error fields if present
          const errorFields = Object.keys(error);
          if (errorFields.length > 0) {
            const errorMessages = errorFields
              .map((field) => `• ${formatFieldName(field)}: ${error[field]}`)
              .join("\n");
            setErrors({
              general: `Validation Errors\n\nThe following fields have errors:\n\n${errorMessages}\n\nPlease correct these errors and try again.`,
            });
          } else {
            setErrors({
              general: "Unexpected Error\n\nAn unexpected error occurred.\n\nPlease try again. If the problem persists, contact support.",
            });
          }
        }
      } else if (error && error.message) {
        setErrors({
          general: `Error\n\n${error.message}\n\nPlease try again.`,
        });
      } else {
        setErrors({
          general: "Unexpected Error\n\nPlease try again. If the problem persists, contact support.",
        });
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  // Validate form
  const validateForm = () => {
    const errors = {};

    if (!eventAsPlanned) {
      errors.eventAsPlanned =
        "Please select whether the event took place as planned.";
    }

    if (eventAsPlanned === TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString()) {
      if (!closingReason) {
        errors.closingReason = "Please select a closing reason.";
      }

      if (
        parseInt(closingReason) === TASK_ITEM_CLOSE_REASON.CANCELLED_BY_OTHER &&
        !closingReasonOther.trim()
      ) {
        errors.closingReasonOther = "Please specify the other closing reason.";
      }
    }

    // Additional comment is optional - no validation needed

    return errors;
  };

  // Event as planned options
  const eventAsPlannedOptions = [
    { value: TASK_ITEM_CLOSE_EVENT_AS_PLANNED.YES.toString(), label: "Yes" },
    { value: TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString(), label: "No" },
  ];

  // Closing reason options (filtered for NO responses)
  const closingReasonOptions = TASK_ITEM_CLOSE_REASON_OPTIONS.filter(
    (option) => option.value !== TASK_ITEM_CLOSE_REASON.SUCCESSFUL, // Exclude "Successful" option
  );

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

  if (!taskItem) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen flex items-center justify-center">
          <Alert variant="error" title="Task Item Not Found">
            The requested task item could not be found.
          </Alert>
        </div>
      </UIXThemeProvider>
    );
  }

  // Check if task is PENDING (locked)
  if (taskItem.status === TASK_ITEM_STATUS.PENDING) {
    return (
      <UIXThemeProvider>
        <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
          <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
            {/* Breadcrumb */}
            <Breadcrumb
              items={[
                {
                  label: "Dashboard",
                  to: "/admin/dashboard",
                  icon: HomeIcon,
                },
                {
                  label: "Task Items",
                  to: "/admin/tasks",
                  icon: ClipboardDocumentListIcon,
                },
                {
                  label: "Close Event Contract Task Item",
                  icon: ClipboardDocumentListIcon,
                  isActive: true,
                },
              ]}
            />

            {/* Locked Message */}
            <Card className="shadow-xl">
              <div className="p-8 sm:p-12 text-center">
                <div className="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-yellow-100 mb-6">
                  <LockClosedIcon className="h-10 w-10 text-yellow-600" />
                </div>
                <h2 className={`text-2xl font-bold ${getThemeClasses("text-primary")} mb-4`}>
                  Task is Locked
                </h2>
                <p className={`${getThemeClasses("text-secondary")} mb-6 max-w-md mx-auto`}>
                  This task is currently pending and will be automatically unlocked after the event end date has passed. Please check back later.
                </p>
                <div className="space-y-4">
                  {taskItem.eventEndDateTime && (
                    <div className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg`}>
                      <p className={`text-sm ${getThemeClasses("text-secondary")} mb-1`}>Event End Date:</p>
                      <p className={`text-lg font-semibold ${getThemeClasses("text-primary")}`}>
                        {new Date(taskItem.eventEndDateTime).toLocaleString()}
                      </p>
                    </div>
                  )}
                  <Button
                    variant="primary"
                    onClick={() => navigate("/admin/tasks")}
                    className="mt-4"
                  >
                    Back to Task List
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className={`min-h-screen ${getThemeClasses("bg-gradient-primary")}`}>
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
          {/* Breadcrumb */}
          <Breadcrumb
            items={[
              {
                label: "Dashboard",
                to: "/admin/dashboard",
                icon: HomeIcon,
              },
              {
                label: "Task Items",
                to: "/admin/tasks",
                icon: ClipboardDocumentListIcon,
              },
              {
                label: "Close Event Contract Task Item",
                icon: ClipboardDocumentListIcon,
                isActive: true,
              },
            ]}
          />

          {/* Success Message */}
          {successMessage && (
            <Alert
              variant="success"
              title="Success"
              className="mb-6"
              icon={CheckCircleIcon}
            >
              {successMessage}
            </Alert>
          )}

          {/* General Error */}
          {errors.general && (
            <div ref={errorRef} className="mb-6">
              <Alert
                variant="error"
                title="Error"
                icon={ExclamationTriangleIcon}
              >
                <div className="whitespace-pre-wrap">{errors.general}</div>
              </Alert>
            </div>
          )}

          {/* Main Content */}
          <Card className="shadow-xl">
            <div className="p-6 sm:p-8">
              {/* Header */}
              <div className="mb-8">
                <div className="flex items-center mb-4">
                  <div
                    className={`p-3 rounded-2xl shadow-lg mr-4 ${getThemeClasses("bg-gradient-secondary")}`}
                  >
                    <ClipboardDocumentListIcon className="h-8 w-8 text-white" />
                  </div>
                  <div>
                    <h1
                      className={`text-2xl sm:text-3xl font-bold ${getThemeClasses("text-primary")}`}
                    >
                      Close Event Contract Task Item
                    </h1>
                    <p
                      className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}
                    >
                      Complete the task closure process
                    </p>
                  </div>
                </div>

                {/* Task Item Info */}
                <div
                  className={`${getThemeClasses("bg-disabled")} p-4 rounded-lg border ${getThemeClasses("border-secondary")}`}
                >
                  <h3 className={`font-medium ${getThemeClasses("text-primary")} mb-2`}>
                    Task Item Details
                  </h3>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className={`font-medium ${getThemeClasses("text-secondary")}`}>Title:</span>
                      <span className="ml-2">
                        {taskItem.title || `Task #${taskItem.id}`}
                      </span>
                    </div>
                    <div>
                      <span className={`font-medium ${getThemeClasses("text-secondary")}`}>Type:</span>
                      <span className="ml-2">
                        {taskItem.typeLabel || "Close Event Contract"}
                      </span>
                    </div>
                    {taskItem.customerName && (
                      <div>
                        <span className={`font-medium ${getThemeClasses("text-secondary")}`}>
                          Customer:
                        </span>
                        <span className="ml-2">{taskItem.customerName}</span>
                      </div>
                    )}
                    {taskItem.facilitatorName && (
                      <div>
                        <span className={`font-medium ${getThemeClasses("text-secondary")}`}>
                          Facilitator:
                        </span>
                        <span className="ml-2">{taskItem.facilitatorName}</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Event Information Section */}
              {(taskItem.eventCategoryName ||
                (taskItem.eventTags && taskItem.eventTags.length > 0) ||
                (taskItem.eventSkillSets &&
                  taskItem.eventSkillSets.length > 0) ||
                (taskItem.eventCertifications &&
                  taskItem.eventCertifications.length > 0) ||
                (taskItem.eventSpecializations &&
                  taskItem.eventSpecializations.length > 0)) && (
                <div
                  className={`${getThemeClasses("bg-disabled")} p-6 rounded-lg border ${getThemeClasses("border-secondary")} mb-6`}
                >
                  <h3
                    className={`text-lg font-semibold mb-4 ${getThemeClasses("text-primary")}`}
                  >
                    Event Information
                  </h3>

                  {/* Event Category */}
                  {taskItem.eventCategoryName && (
                    <div className="mb-4">
                      <label className={`block text-sm font-medium ${getThemeClasses("text-secondary")} mb-2`}>
                        <FolderIcon className="inline-block w-4 h-4 mr-1" />
                        Event Category
                      </label>
                      <div>
                        <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
                          {taskItem.eventCategoryName}
                        </span>
                        {taskItem.eventCategoryDescription && (
                          <p className={`text-sm ${getThemeClasses("text-muted")} mt-2`}>
                            {taskItem.eventCategoryDescription}
                          </p>
                        )}
                      </div>
                    </div>
                  )}

                  {/* Event Tags */}
                  {taskItem.eventTags && taskItem.eventTags.length > 0 && (
                    <BadgeList
                      items={taskItem.eventTags}
                      icon={TagIcon}
                      label="Event Tags"
                    />
                  )}

                  {/* Event Skill Sets */}
                  {taskItem.eventSkillSets &&
                    taskItem.eventSkillSets.length > 0 && (
                      <BadgeList
                        items={taskItem.eventSkillSets}
                        icon={CpuChipIcon}
                        label="Required Skill Sets"
                      />
                    )}

                  {/* Event Certifications */}
                  {taskItem.eventCertifications &&
                    taskItem.eventCertifications.length > 0 && (
                      <BadgeList
                        items={taskItem.eventCertifications}
                        icon={AcademicCapIcon}
                        label="Required Certifications"
                      />
                    )}

                  {/* Event Specializations */}
                  {taskItem.eventSpecializations &&
                    taskItem.eventSpecializations.length > 0 && (
                      <BadgeList
                        items={taskItem.eventSpecializations}
                        icon={ShieldCheckIcon}
                        label="Required Specializations"
                      />
                    )}
                </div>
              )}

              {/* Close Task Form */}
              <form onSubmit={handleSubmit} className="space-y-6">
                {/* 1. Did event take place as planned? (Mandatory) */}
                <div>
                  <RadioGroup
                    label="Did this event take place as planned?"
                    name="eventAsPlanned"
                    value={eventAsPlanned}
                    onChange={handleEventAsPlannedChange}
                    options={eventAsPlannedOptions}
                    error={errors.eventAsPlanned}
                    required
                  />
                </div>

                {/* 2. Closing Reason (Only shown for NO) */}
                {eventAsPlanned ===
                  TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString() && (
                  <div>
                    <Select
                      label="Reason for not taking place"
                      name="closingReason"
                      value={closingReason}
                      onChange={handleClosingReasonChange}
                      options={[
                        { value: "", label: "Please select a reason" },
                        ...closingReasonOptions,
                      ]}
                      error={errors.closingReason}
                      required
                    />
                  </div>
                )}

                {/* 3. Other Reason (Only shown for "Other" selection) */}
                {eventAsPlanned ===
                  TASK_ITEM_CLOSE_EVENT_AS_PLANNED.NO.toString() &&
                  parseInt(closingReason) ===
                    TASK_ITEM_CLOSE_REASON.CANCELLED_BY_OTHER && (
                    <div>
                      <TextArea
                        label="Please specify the other reason"
                        name="closingReasonOther"
                        value={closingReasonOther}
                        onChange={setClosingReasonOther}
                        placeholder="Please provide details..."
                        error={errors.closingReasonOther}
                        required
                        rows={3}
                      />
                    </div>
                  )}

                {/* 4. Additional Comments (Optional) */}
                <div>
                  <TextArea
                    label="Additional Comments"
                    name="additionalComment"
                    value={additionalComment}
                    onChange={setAdditionalComment}
                    placeholder="Enter additional comments (optional)..."
                    error={errors.additionalComment}
                    rows={4}
                    helpText="Optional field for any additional information about the task closure."
                  />
                </div>

                {/* Action Buttons */}
                <div className="flex flex-col sm:flex-row gap-4 pt-6">
                  <Button
                    type="submit"
                    variant="primary"
                    size="lg"
                    disabled={isSubmitting}
                    isLoading={isSubmitting}
                    className="w-full sm:w-auto"
                  >
                    {isSubmitting
                      ? "Closing Task..."
                      : "Close Event Contract Task Item"}
                  </Button>

                  <Button
                    type="button"
                    variant="secondary"
                    size="lg"
                    onClick={() => navigate("/admin/tasks")}
                    disabled={isSubmitting}
                    className="w-full sm:w-auto"
                  >
                    Cancel
                  </Button>
                </div>
              </form>
            </div>
          </Card>
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemCloseEventContractPage;
