// File Path: monorepo/web/frontend/src/pages/Admin/TaskItem/AssignFacilitatorOrSpeaker/Step4Page.jsx

import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UIXThemeProvider,
  StaffWizardFormStep,
  FormSection,
  RadioGroup,
  Select,
  Alert,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  UserGroupIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";

function AdminTaskItemAssignFacilitatorOrSpeakerStep4Page() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { getThemeClasses } = useUIXTheme();

  const [selectedRole, setSelectedRole] = useState("");
  const [hasAccepted, setHasAccepted] = useState("");
  const [acceptanceMethod, setAcceptanceMethod] = useState("");
  const [declineReason, setDeclineReason] = useState("");
  const [errors, setErrors] = useState({});

  const wizardSteps = [
    { title: "Event Details" },
    { title: "Select Person" },
    { title: "Acceptance Status" },
    { title: "Review & Submit" },
  ];

  // Load saved data from sessionStorage
  useEffect(() => {
    const savedRole = sessionStorage.getItem(`assign_facilitator_speaker_${id}_role`);
    const savedAcceptance = sessionStorage.getItem(`assign_facilitator_speaker_${id}_accepted`);
    const savedMethod = sessionStorage.getItem(`assign_facilitator_speaker_${id}_acceptance_method`);
    const savedDecline = sessionStorage.getItem(`assign_facilitator_speaker_${id}_decline_reason`);

    if (!savedRole) {
      // If no role selected, redirect back to step 1
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-1`);
      return;
    }

    setSelectedRole(savedRole);
    if (savedAcceptance) setHasAccepted(savedAcceptance);
    if (savedMethod) setAcceptanceMethod(savedMethod);
    if (savedDecline) setDeclineReason(savedDecline);
  }, [id, navigate]);

  const acceptanceOptions = [
    {
      value: "yes",
      label: "Yes",
      description: `The ${selectedRole} has accepted this assignment`
    },
    {
      value: "no",
      label: "No",
      description: `The ${selectedRole} has declined this assignment`
    },
  ];

  const acceptanceMethodOptions = [
    { value: "", label: "Please select" },
    { value: "pre-approval", label: "Pre-approval" },
    { value: "telephone", label: "Telephone" },
    { value: "email", label: "Email" },
    { value: "text", label: "Text" },
  ];

  const declineReasonOptions = [
    { value: "", label: "Please select" },
    { value: "unavailable", label: "Unavailable" },
    { value: "does-not-want-client", label: "Does not want this client" },
    { value: "unable-to-travel", label: "Unable to travel" },
    { value: "event-not-suitable", label: "Type of event not suitable" },
    { value: "pay-dispute", label: "Pay dispute" },
    { value: "on-vacation", label: "On vacation" },
    { value: "illness-or-injury", label: "Illness or injury" },
  ];

  const handleNext = () => {
    const newErrors = {};

    if (!hasAccepted) {
      newErrors.accepted = "Please indicate if the assignment has been accepted";
    }

    if (hasAccepted === "yes" && !acceptanceMethod) {
      newErrors.method = "Please select how the assignment was accepted";
    }

    if (hasAccepted === "no" && !declineReason) {
      newErrors.reason = "Please select why the assignment was declined";
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }

    // Save selections to sessionStorage
    sessionStorage.setItem(`assign_facilitator_speaker_${id}_accepted`, hasAccepted);
    if (hasAccepted === "yes") {
      sessionStorage.setItem(`assign_facilitator_speaker_${id}_acceptance_method`, acceptanceMethod);
      sessionStorage.removeItem(`assign_facilitator_speaker_${id}_decline_reason`);
    } else {
      sessionStorage.setItem(`assign_facilitator_speaker_${id}_decline_reason`, declineReason);
      sessionStorage.removeItem(`assign_facilitator_speaker_${id}_acceptance_method`);
    }
    setErrors({});

    navigate(`/admin/task/${id}/assign-facilitator-speaker/step-5`);
  };

  const handleBack = () => {
    // Navigate back to the appropriate step 3 page based on saved role
    if (selectedRole === "facilitator") {
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-3-facilitator`);
    } else {
      navigate(`/admin/task/${id}/assign-facilitator-speaker/step-3-speaker`);
    }
  };

  const handleCancel = () => {
    // Clear all sessionStorage on cancel
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_role`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_person_id`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_hours`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_accepted`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_acceptance_method`);
    sessionStorage.removeItem(`assign_facilitator_speaker_${id}_decline_reason`);
    navigate("/admin/tasks");
  };

  const handleAcceptanceChange = (value) => {
    setHasAccepted(value);
    // Clear the other field when changing acceptance status
    if (value === "yes") {
      setDeclineReason("");
    } else {
      setAcceptanceMethod("");
    }
  };

  return (
    <UIXThemeProvider>
      <StaffWizardFormStep
        wizardSteps={wizardSteps}
        currentStep={3}
        wizardTitle="Assign Facilitator or Speaker"
        wizardIcon={UserGroupIcon}
        stepTitle="Acceptance Status"
        stepSubtitle={`Has the ${selectedRole} accepted or declined this assignment?`}
        stepIcon={CheckCircleIcon}
        errors={errors}
        showFormCard={true}
        actionLayout="between"
        contentMaxWidth="4xl"
        showActions={true}
        actions={[
          {
            label: "Next: Review & Submit",
            variant: "primary",
            onClick: handleNext,
          },
        ]}
        onBack={handleBack}
        onCancel={handleCancel}
        backLabel="Back"
        cancelLabel="Cancel"
      >
        <FormSection
          title="Acceptance Status"
          description={`Has the ${selectedRole} accepted this contract?`}
          className="mb-6"
        >
          <RadioGroup
            label={`Has the ${selectedRole} accepted this contract?`}
            options={acceptanceOptions}
            value={hasAccepted}
            onChange={handleAcceptanceChange}
            error={errors.accepted}
            required={true}
          />
        </FormSection>

        {/* Show acceptance method dropdown if accepted */}
        {hasAccepted === "yes" && (
          <FormSection
            title="How Was It Accepted?"
            description="Select the method by which the assignment was accepted"
            className="mb-6"
          >
            <div className="space-y-2">
              <label className={`block text-sm font-medium ${getThemeClasses("text-primary")}`}>
                Acceptance Method <span className="text-red-500">*</span>
              </label>
              <select
                value={acceptanceMethod}
                onChange={(e) => {
                  if (import.meta.env.DEV) {
                    console.log("Acceptance method changed:", e.target.value);
                  }
                  setAcceptanceMethod(e.target.value);
                }}
                className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${
                  errors.method ? "border-red-500" : getThemeClasses("border-secondary")
                }`}
              >
                {acceptanceMethodOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.method && (
                <p className="text-sm text-red-600">{errors.method}</p>
              )}
              <p className={`text-sm ${getThemeClasses("text-muted")}`}>
                Select how the assignment was accepted
              </p>
            </div>
          </FormSection>
        )}

        {/* Show decline reason dropdown if declined */}
        {hasAccepted === "no" && (
          <FormSection
            title="Why Was It Declined?"
            description="Select the reason for declining the assignment"
            className="mb-6"
          >
            <div className="space-y-2">
              <label className={`block text-sm font-medium ${getThemeClasses("text-primary")}`}>
                Decline Reason <span className="text-red-500">*</span>
              </label>
              <select
                value={declineReason}
                onChange={(e) => {
                  if (import.meta.env.DEV) {
                    console.log("Decline reason changed:", e.target.value);
                  }
                  setDeclineReason(e.target.value);
                }}
                className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500 ${
                  errors.reason ? "border-red-500" : getThemeClasses("border-secondary")
                }`}
              >
                {declineReasonOptions.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
              {errors.reason && (
                <p className="text-sm text-red-600">{errors.reason}</p>
              )}
              <p className={`text-sm ${getThemeClasses("text-muted")}`}>
                Select why the assignment was declined
              </p>
            </div>
          </FormSection>
        )}

        {hasAccepted && (
          <Alert
            variant={hasAccepted === "yes" ? "success" : "warning"}
            icon={ExclamationTriangleIcon}
          >
            <p className="font-semibold mb-2">
              {hasAccepted === "yes" ? "Assignment Accepted" : "Assignment Declined"}
            </p>
            <p>
              {hasAccepted === "yes"
                ? "The assignment has been accepted. Proceed to review and submit."
                : "The assignment has been declined. You may still submit this information for record-keeping purposes."}
            </p>
          </Alert>
        )}
      </StaffWizardFormStep>
    </UIXThemeProvider>
  );
}

export default AdminTaskItemAssignFacilitatorOrSpeakerStep4Page;