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

import React, { useState, useEffect, useCallback, useMemo, memo } from "react";
import { useNavigate } from "react-router";
import { useStaffAddWizardStorage } from "../../../../services/Services";
import {
  UserPlusIcon,
  TagIcon,
  UserIcon,
  ChatBubbleBottomCenterTextIcon,
  ChartBarIcon,
  ArrowRightIcon,
  CalendarDaysIcon,
} from "@heroicons/react/24/outline";
import {
  StaffWizardFormStep,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  DateInput,
  DatePicker,
  Textarea,
  CheckboxGroup,
  UIXThemeProvider,
  useUIXTheme,
} from "../../../../components/UIX";

// Import business components
import { TagsMultiSelect } from "../../../../components/business";

// Import constants
import {
  IDENTIFY_AS_OPTIONS,
  GENDER_OPTIONS_WITH_EMPTY_OPTION,
} from "../../../../constants/FieldOptions";
import {
  STAFF_GENDER_OTHER,
} from "../../../../constants/Staff";

// Wizard configuration (static, moved outside component)
const WIZARD_STEPS = [
  { 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: "Review", subtitle: "Confirm", isActive: false, isCompleted: false },
];

// Memoized content component
const Step6Content = memo(function Step6Content() {
  const navigate = useNavigate();
  const wizardStorage = useStaffAddWizardStorage();
  const { getThemeClasses } = useUIXTheme();

  // PERFORMANCE: Memoize wizardState to prevent unnecessary re-computation
  const wizardState = useMemo(() => wizardStorage.getWizardState(), [wizardStorage]);

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

  // Form data from wizard state
  const [tags, setTags] = useState(wizardState.tags || []);
  const [identifyAs, setIdentifyAs] = useState(Array.isArray(wizardState.identifyAs) ? wizardState.identifyAs : []);
  const [gender, setGender] = useState(wizardState.gender || 0);
  const [genderOther, setGenderOther] = useState(wizardState.genderOther || "");
  const [birthDate, setBirthDate] = useState(wizardState.birthDate || "");
  const [joinDate, setJoinDate] = useState(wizardState.joinDate || new Date().toISOString().split('T')[0]);
  const [additionalComment, setAdditionalComment] = useState(
    wizardState.additionalComment || "",
  );

  // 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 onUnauthorized = useCallback(() => {
    navigate("/admin/staff");
  }, [navigate]);

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

    let newErrors = {};
    let hasErrors = false;

    // Basic validation
    if (gender === STAFF_GENDER_OTHER && genderOther && !genderOther.trim()) {
      newErrors.genderOther = "Please specify other gender";
      hasErrors = true;
    }

    if (!joinDate) {
      newErrors.joinDate = "Join 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,
      birthDate,
      joinDate,
      gender,
      genderOther,
      additionalComment,
      identifyAs,
    });

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


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

  const handleIdentifyAsChange = useCallback((valuesObject) => {
    // Convert object back to array format that the backend expects
    const selectedValues = Object.keys(valuesObject)
      .filter(key => valuesObject[key])
      .map(key => parseInt(key, 10));

    setIdentifyAs(selectedValues);
  }, []);


  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);
  }, []);

  // Memoized theme classes
  const themeClasses = useMemo(() => ({
    bgGradientPrimary: getThemeClasses('bg-gradient-primary'),
    borderPrimary: getThemeClasses('border-primary'),
  }), [getThemeClasses]);

  // 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 Review",
      variant: "primary",
      icon: ArrowRightIcon,
      onClick: onSubmitClick,
      disabled: isLoading,
    }
  ], [onSubmitClick, isLoading]);

  return (
    <div className={`min-h-screen ${themeClasses.bgGradientPrimary || '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 ${themeClasses.borderPrimary}`}></div>
              <span className="ml-3 text-gray-600">Submitting...</span>
            </div>
          </div>
        ) : (
          <StaffWizardFormStep
            wizardSteps={WIZARD_STEPS}
            currentStep={6}
            wizardTitle="Add New Staff Member"
            wizardIcon={UserPlusIcon}
            stepTitle="Metrics"
            stepSubtitle="Performance and additional 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>
                  <div className="w-full">
                    <TagsMultiSelect
                      label="Tags"
                      value={tags}
                      onChange={handleTagsChange}
                      error={errors.tags}
                      required={false}
                      onUnauthorized={onUnauthorized}
                      className="w-full"
                    />
                  </div>
                </FormRow>

                <FormRow>
                  <CheckboxGroup
                    label="Do you identify as belonging to any of the following groups?"
                    options={IDENTIFY_AS_OPTIONS.map(opt => ({ ...opt, key: String(opt.value) }))}
                    value={Array.isArray(identifyAs) ? identifyAs.reduce((obj, value) => ({ ...obj, [String(value)]: true }), {}) : {}}
                    onChange={handleIdentifyAsChange}
                    error={errors.identifyAs}
                    required={false}
                  />
                </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={false}
                  />
                </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={false}
                    icon={CalendarDaysIcon}
                    placeholder="Select birth date"
                  />
                  <DateInput
                    label="Join Date"
                    value={joinDate}
                    onChange={handleJoinDateChange}
                    helperText="The date this staff member joined the organization"
                    error={errors.joinDate}
                    required={true}
                    icon={CalendarDaysIcon}
                    placeholder="Select join date"
                  />
                </FormRow>
              </FormSection>
            </FormCard>

            {/* Additional Comments Section */}
            <FormCard
              title="Additional Information"
              icon={ChatBubbleBottomCenterTextIcon}
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <div className="w-full">
                  <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}
                  />
                </div>
              </FormSection>
            </FormCard>
          </StaffWizardFormStep>
        )}
      </div>
    </div>
  );
});

Step6Content.displayName = 'Step6Content';

function AdminStaffAddStep6Page() {
  return (
    <UIXThemeProvider>
      <Step6Content />
    </UIXThemeProvider>
  );
}

export default AdminStaffAddStep6Page;