// File Path: monorepo/web/frontend/src/pages/Admin/Staff/Add/Step6Page.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import { useStaffAddWizardStorage } from "../../../../services/Services";
import {
  UserPlusIcon,
  ArrowRightIcon,
  TagIcon,
  CalendarIcon,
  ChatBubbleBottomCenterTextIcon,
  UserIcon,
  QuestionMarkCircleIcon,
} from "@heroicons/react/24/outline";
import {
  TagsMultiSelect,
  HowHearAboutUsSelect,
} from "../../../../components/business/selects";
import {
  GENDER_OPTIONS_WITH_EMPTY_OPTION,
  IDENTIFY_AS_OPTIONS,
} from "../../../../constants/FieldOptions";
import { STAFF_GENDER_OTHER } from "../../../../constants/Staff";
import {
  StaffWizardFormStep,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Textarea,
  CheckboxGroup,
} from "../../../../components/UIX";


function AdminStaffAddStep6Page() {
  const navigate = useNavigate();
  const wizardStorage = useStaffAddWizardStorage();
  const wizardState = wizardStorage.getWizardState();

  // Component states
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [showCancelWarning, setShowCancelWarning] = useState(false);

  // Form data
  const [tags, setTags] = useState(wizardState.tags || []);
  const [howDidYouHearAboutUsID, setHowDidYouHearAboutUsID] = useState(
    wizardState.howDidYouHearAboutUsID || "",
  );
  const [isHowDidYouHearAboutUsOther, setIsHowDidYouHearAboutUsOther] =
    useState(wizardState.isHowDidYouHearAboutUsOther || false);
  const [howDidYouHearAboutUsOther, setHowDidYouHearAboutUsOther] = useState(
    wizardState.howDidYouHearAboutUsOther || "",
  );
  const [birthDate, setBirthDate] = useState(wizardState.birthDate || "");
  const [joinDate, setJoinDate] = useState(
    wizardState.joinDate || new Date().toISOString().split("T")[0],
  );
  const [gender, setGender] = useState(wizardState.gender || 0);
  const [genderOther, setGenderOther] = useState(wizardState.genderOther || "");
  const [additionalComment, setAdditionalComment] = useState(
    wizardState.additionalComment || "",
  );
  const [identifyAs, setIdentifyAs] = useState(wizardState.identifyAs || []);

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

  // Scroll to top on mount only
  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  // Check for existing state and redirect if needed
  useEffect(() => {
    // If no wizard state exists, redirect back to step 1
    if (!wizardState || Object.keys(wizardState).length === 0) {
      navigate("/admin/staff/add/step-1-search");
    }
  }, [wizardState, navigate]);

  const handleCancel = () => {
    setShowCancelWarning(true);
  };

  const handleConfirmCancel = () => {
    wizardStorage.clearWizardState();
    navigate("/admin/staff");
  };

  // Memoized input handlers to prevent re-rendering and focus issues
  const handleBirthDateChange = useCallback((value) => {
    setBirthDate(value);
  }, []);

  const handleJoinDateChange = useCallback((value) => {
    setJoinDate(value);
  }, []);

  const handleGenderChange = useCallback((value) => {
    setGender(parseInt(value));
  }, []);

  const handleGenderOtherChange = useCallback((value) => {
    setGenderOther(value);
  }, []);

  const handleAdditionalCommentChange = useCallback((e) => {
    setAdditionalComment(e.target.value);
  }, []);

  const handleHowDidYouHearAboutUsOtherChange = useCallback((value) => {
    setHowDidYouHearAboutUsOther(value);
  }, []);

  const handleIdentifyAsChange = useCallback((selectedValues) => {
    setIdentifyAs(selectedValues);
  }, []);

  const onSubmitClick = useCallback((e) => {
    e.preventDefault();
    setErrors({});

    let newErrors = {};
    let hasErrors = false;

    // Basic validation
    if (!howDidYouHearAboutUsID) {
      newErrors.howDidYouHearAboutUsID =
        "Please specify how you heard about us";
      hasErrors = true;
    } else if (
      isHowDidYouHearAboutUsOther &&
      !howDidYouHearAboutUsOther.trim()
    ) {
      newErrors.howDidYouHearAboutUsOther = "Please specify other option";
      hasErrors = true;
    }

    if (gender === 0) {
      newErrors.gender = "Gender is required";
      hasErrors = true;
    } else if (gender === STAFF_GENDER_OTHER && !genderOther.trim()) {
      newErrors.genderOther = "Please specify other gender";
      hasErrors = true;
    }

    if (!birthDate) {
      newErrors.birthDate = "Birth date is required";
      hasErrors = true;
    }

    if (hasErrors) {
      setErrors(newErrors);
      // Scroll to top to show errors
      window.scrollTo(0, 0);
      return;
    }

    // Save to wizard storage
    wizardStorage.updateWizardState({
      tags,
      howDidYouHearAboutUsID,
      isHowDidYouHearAboutUsOther,
      howDidYouHearAboutUsOther,
      birthDate,
      joinDate,
      gender,
      genderOther,
      additionalComment,
      identifyAs,
    });

    navigate("/admin/staff/add/step-7");
  }, [tags, howDidYouHearAboutUsID, isHowDidYouHearAboutUsOther, howDidYouHearAboutUsOther, birthDate, joinDate, gender, genderOther, additionalComment, identifyAs, wizardStorage, navigate]);

  const handleHowHearChange = useCallback((value) => {
    setHowDidYouHearAboutUsID(value);
    // Clear error when user selects a value
    if (errors.howDidYouHearAboutUsID) {
      setErrors({ ...errors, howDidYouHearAboutUsID: null });
    }
  }, [errors]);

  const handleHowHearOtherDetected = useCallback((isOther) => {
    setIsHowDidYouHearAboutUsOther(isOther);
    if (!isOther) {
      setHowDidYouHearAboutUsOther(""); // Clear other field if not "Other"
    }
  }, []);

  // Additional memoized handlers for UIX components
  const handleTagsChange = useCallback((value) => {
    setTags(value);
  }, []);

  const handleIdentifyAsChange = useCallback((values) => {
    setIdentifyAs(values);
  }, []);

  const handleHowDidYouHearAboutUsOtherChange = useCallback((value) => {
    setHowDidYouHearAboutUsOther(value);
  }, []);

  const handleGenderChange = useCallback((value) => {
    setGender(parseInt(value));
  }, []);

  const handleGenderOtherChange = useCallback((value) => {
    setGenderOther(value);
  }, []);

  const handleBirthDateChange = useCallback((value) => {
    setBirthDate(value);
  }, []);

  const handleJoinDateChange = useCallback((value) => {
    setJoinDate(value);
  }, []);

  const handleAdditionalCommentChange = useCallback((e) => {
    setAdditionalComment(e.target.value);
  }, []);

  // Wizard configuration
  const wizardSteps = useMemo(() => [
    { id: 1, title: "Search", subtitle: "Find Staff", isActive: false, isCompleted: true },
    { id: 2, title: "Type", subtitle: "Select Type", isActive: false, isCompleted: true },
    { id: 3, title: "Contact", subtitle: "Information", isActive: false, isCompleted: true },
    { id: 4, title: "Address", subtitle: "Location", isActive: false, isCompleted: true },
    { id: 5, title: "Account", subtitle: "Settings", isActive: false, isCompleted: true },
    { id: 6, title: "Metrics", subtitle: "Performance", isActive: true, isCompleted: false },
    { id: 7, title: "Comments", subtitle: "Notes", isActive: false, isCompleted: false },
  ], []);

  // Navigation handlers
  const handleBack = useCallback(() => {
    navigate("/admin/staff/add/step-5");
  }, [navigate]);

  const handleCancel = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

  // Action configuration
  const actions = useMemo(() => [
    {
      label: "Continue to Comments",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: onSubmitClick,
      disabled: isLoading,
    }
  ], [onSubmitClick, isLoading]);

  return (
    <div className="min-h-screen bg-gray-50 px-4 sm:px-6 lg:px-8">
      <div className="max-w-7xl mx-auto py-6 sm:py-8">
        {/* Loading State */}
        {isLoading ? (
          <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
            <div className="flex items-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600">Submitting...</span>
            </div>
          </div>
        ) : (
          <StaffWizardFormStep
            wizardSteps={wizardSteps}
            currentStep={6}
            wizardTitle="Add New Staff Member"
            wizardIcon={UserPlusIcon}
            stepTitle="Metrics & Performance"
            stepSubtitle="Add performance metrics and demographic information"
            stepIcon={ChartBarIcon}
            showFormCard={false}
            contentMaxWidth="7xl"
            errors={errors}
            isLoading={isLoading}
            actions={actions}
            onCancel={handleCancel}
            onBack={handleBack}
            actionLayout="end"
          >
            {/* Tags and Identification Section */}
            <FormCard
              title="Tags & Identification"
              icon={TagIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow>
                  <TagsMultiSelect
                    label="Tags"
                    value={tags}
                    onChange={handleTagsChange}
                    error={errors.tags}
                    required={false}
                    onUnauthorized={onUnauthorized}
                  />
                </FormRow>

                <FormRow>
                  <CheckboxGroup
                    label="Do you identify as belonging to any of the following groups?"
                    options={IDENTIFY_AS_OPTIONS}
                    selectedValues={identifyAs}
                    onChange={handleIdentifyAsChange}
                    error={errors.identifyAs}
                    required={false}
                  />
                </FormRow>
              </FormSection>
            </FormCard>
          </h1>
          <p className="mt-1 text-xs sm:text-sm text-gray-600 flex items-center">
            <InformationCircleIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1 flex-shrink-0" />
            Add metrics and demographic information
          </p>
        </div>


          {/* Desktop Wizard Steps */}
          <div className="hidden md:flex items-center justify-center overflow-x-auto pb-2">
            <div className="flex items-center min-w-max">
              {/* Steps 1-5 Complete */}
              {[1, 2, 3, 4, 5].map((step, index) => (
                <React.Fragment key={step}>
                  <div className="flex items-center">
                    <div className="flex items-center justify-center w-10 h-10 bg-green-600 rounded-full">
                      <CheckIcon className="w-6 h-6 text-white" />
                    </div>
                    <div className="ml-3">
                      <p className="text-sm font-medium text-gray-900">
                        {step === 1 && "Search"}
                        {step === 2 && "Type"}
                        {step === 3 && "Contact"}
                        {step === 4 && "Address"}
                        {step === 5 && "Account"}
                      </p>
                      <p className="text-xs text-gray-500">Complete</p>
                    </div>
                  </div>
                  {index < 6 && (
                    <div className="mx-2 w-12 h-0.5 bg-green-600"></div>
                  )}
                </React.Fragment>
              ))}

              {/* Step 6 - Active */}
              <div className="flex items-center">
                <div className="flex items-center justify-center w-10 h-10 bg-blue-600 rounded-full">
                  <span className="text-white font-semibold">6</span>
                </div>
                <div className="ml-3">
                  <p className="text-sm font-medium text-gray-900">Metrics</p>
                  <p className="text-xs text-gray-500">Performance</p>
                </div>
              </div>

              <div className="mx-2 w-12 h-0.5 bg-gray-300"></div>

              {/* Step 7 Inactive */}
              <div className="flex items-center">
                <div className="flex items-center justify-center w-10 h-10 bg-gray-300 rounded-full">
                  <span className="text-gray-600 font-semibold">7</span>
                </div>
                <div className="ml-3">
                  <p className="text-sm font-medium text-gray-500">Comments</p>
                  <p className="text-xs text-gray-400">Notes</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Error Message */}
        {errors.general && (
          <div className="mb-4 bg-red-50 border border-red-200 text-red-700 px-3 sm:px-4 py-2 sm:py-3 rounded-lg text-sm sm:text-base">
            <div className="flex justify-between items-center">
              <span className="flex items-center break-words">
                <ExclamationCircleIcon className="w-4 sm:w-5 h-4 sm:h-5 mr-2 flex-shrink-0" />
                {errors.general}
              </span>
              <button
                onClick={() => setErrors({})}
                className="text-red-700 hover:text-red-900 ml-2 flex-shrink-0"
              >
                ×
              </button>
            </div>
          </div>
        )}

        {/* Main Content */}
        {isLoading ? (
          <div className="bg-white shadow-sm rounded-lg p-8">
            <div className="flex items-center justify-center">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600">Submitting...</span>
            </div>
          </div>
        ) : (
          <StaffWizardFormStep
            wizardSteps={wizardSteps}
            currentStep={6}
            wizardTitle="Add New Staff Member"
            wizardIcon={UserPlusIcon}
            stepTitle="Metrics & Performance"
            stepSubtitle="Add performance metrics and demographic information"
            stepIcon={ChartBarIcon}
            showFormCard={false}
            contentMaxWidth="7xl"
            errors={errors}
            isLoading={isLoading}
            actions={actions}
            onCancel={handleCancel}
            onBack={handleBack}
            actionLayout="end"
          >
            {/* Tags and Identification Section */}
            <FormCard
              title="Tags & Identification"
              icon={TagIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow>
                  <TagsMultiSelect
                    label="Tags"
                    value={tags}
                    onChange={handleTagsChange}
                    error={errors.tags}
                    required={false}
                    onUnauthorized={onUnauthorized}
                  />
                </FormRow>

                <FormRow>
                  <CheckboxGroup
                    label="Do you identify as belonging to any of the following groups?"
                    options={IDENTIFY_AS_OPTIONS}
                    selectedValues={identifyAs}
                    onChange={handleIdentifyAsChange}
                    error={errors.identifyAs}
                    required={false}
                  />
                </FormRow>
              </FormSection>
            </FormCard>

            {/* Discovery & Marketing Section */}
            <FormCard
              title="Discovery & Marketing"
              icon={QuestionMarkCircleIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow>
                  <HowHearAboutUsSelect
                    value={howDidYouHearAboutUsID}
                    onChange={handleHowHearChange}
                    onOtherDetected={handleHowHearOtherDetected}
                    error={errors.howDidYouHearAboutUsID}
                    required={true}
                    onUnauthorized={onUnauthorized}
                  />
                </FormRow>

                {/* Show additional input field if "Other" is selected */}
                {isHowDidYouHearAboutUsOther && (
                  <FormRow>
                    <Input
                      label="How did you hear about us? (Other)"
                      value={howDidYouHearAboutUsOther}
                      onChange={handleHowDidYouHearAboutUsOtherChange}
                      placeholder="Please specify"
                      error={errors.howDidYouHearAboutUsOther}
                      required={true}
                    />
                  </FormRow>
                )}
              </FormSection>
            </FormCard>

            {/* Personal Information Section */}
            <FormCard
              title="Personal Information"
              icon={UserIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow>
                  <Select
                    label="Gender"
                    value={String(gender)}
                    onChange={handleGenderChange}
                    options={GENDER_OPTIONS_WITH_EMPTY_OPTION}
                    error={errors.gender}
                    required={true}
                  />
                </FormRow>

                {gender === STAFF_GENDER_OTHER && (
                  <FormRow>
                    <Input
                      label="Gender (Other)"
                      value={genderOther}
                      onChange={handleGenderOtherChange}
                      placeholder="Please specify"
                      error={errors.genderOther}
                      required={true}
                    />
                  </FormRow>
                )}

                <FormRow cols={2}>
                  <DateInput
                    label="Birth Date"
                    value={birthDate}
                    onChange={handleBirthDateChange}
                    error={errors.birthDate}
                    required={true}
                  />
                  <DateInput
                    label="Join Date"
                    value={joinDate}
                    onChange={handleJoinDateChange}
                    helperText="The date this staff member joined the organization"
                    error={errors.joinDate}
                    required={false}
                  />
                </FormRow>
              </FormSection>
            </FormCard>

            {/* Additional Comments Section */}
            <FormCard
              title="Additional Information"
              icon={ChatBubbleBottomCenterTextIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow>
                  <Textarea
                    label="Additional Comment"
                    value={additionalComment}
                    onChange={handleAdditionalCommentChange}
                    placeholder="Enter any additional comments or notes about this staff member"
                    rows={4}
                    maxLength={638}
                    error={errors.additionalComment}
                    required={false}
                    showCharacterCount={true}
                  />
                </FormRow>
              </FormSection>
            </FormCard>
          </StaffWizardFormStep>
        )}
      </div>

      {/* Cancel Confirmation Modal - Responsive */}
      {showCancelWarning && (
        <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-md w-full">
            <div className="px-4 sm:px-6 py-4 border-b border-gray-200">
              <h3 className="text-base sm:text-lg font-semibold text-gray-900 flex items-center">
                <ExclamationTriangleIcon className="h-5 w-5 mr-2 text-amber-600" />
                Are you sure?
              </h3>
            </div>

            <div className="px-4 sm:px-6 py-4">
              <p className="text-sm text-gray-600">
                Your Staff record will be cancelled and your work will be lost.
                This cannot be undone. Do you want to continue?
              </p>
            </div>

            <div className="px-4 sm:px-6 py-4 bg-gray-50 border-t border-gray-200 flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
              <button
                onClick={() => setShowCancelWarning(false)}
                className="w-full sm:w-auto px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                No, Keep Working
              </button>
              <button
                onClick={handleConfirmCancel}
                className="w-full sm:w-auto px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700"
              >
                Yes, Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default AdminStaffAddStep6Page;
