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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  ChatBubbleBottomCenterIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  TagIcon,
  CalendarIcon,
  ChatBubbleBottomCenterTextIcon,
  UserIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Textarea,
  Button,
  Alert,
} from "../../../../components/UIX";
import {
  TagsMultiSelect,
} from "../../../../components/business/selects";
import {
  SPEAKER_IS_JOB_SEEKER_NO,
  SPEAKER_GENDER_OTHER,
  SPEAKER_GENDER_MALE,
  SPEAKER_GENDER_FEMALE,
  SPEAKER_GENDER_PREFER_NOT_TO_SAY,
  SPEAKER_STATUS_IN_COUNTRY_PERMANENT_RESIDENT,
  SPEAKER_STATUS_IN_COUNTRY_NATURALIZED_CITIZEN,
  SPEAKER_STATUS_IN_COUNTRY_PROTECTED_PERSON,
  SPEAKER_STATUS_IN_COUNTRY_OTHER,
  SPEAKER_MARITAL_STATUS_OTHER,
  SPEAKER_EDUCATION_OTHER,
  SPEAKER_IS_JOB_SEEKER_YES,
} from "../../../../constants/Speaker";

// Wizard steps configuration - moved outside component
const WIZARD_STEPS = [
  { title: "Search", isCompleted: true },
  { title: "Type", isCompleted: true },
  { title: "Contact", isCompleted: true },
  { title: "Address", isCompleted: true },
  { title: "Account", isCompleted: true },
  { title: "Metrics", isCompleted: false },
  { title: "Review" },
];

// Gender options - moved outside component
const GENDER_OPTIONS = [
  { value: "0", label: "Please select" },
  { value: String(SPEAKER_GENDER_MALE), label: "Male" },
  { value: String(SPEAKER_GENDER_FEMALE), label: "Female" },
  { value: String(SPEAKER_GENDER_OTHER), label: "Other" },
  { value: String(SPEAKER_GENDER_PREFER_NOT_TO_SAY), label: "Prefer not to say" },
];

function AdminSpeakerAddStep6Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();

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

  // Job seeker and metrics form data
  const [isJobSeeker] = useState(SPEAKER_IS_JOB_SEEKER_NO);
  const [tags, setTags] = useState([]);
  const [joinDate, setJoinDate] = useState(new Date().toISOString().split("T")[0]);
  const [gender, setGender] = useState(0);
  const [genderOther, setGenderOther] = useState("");
  const [additionalComment, setAdditionalComment] = useState("");
  const [statusInCountry, setStatusInCountry] = useState(0);
  const [statusInCountryOther, setStatusInCountryOther] = useState("");
  const [countryOfOrigin, setCountryOfOrigin] = useState("");
  const [dateOfEntryIntoCountry, setDateOfEntryIntoCountry] = useState("");
  const [maritalStatus, setMaritalStatus] = useState(0);
  const [maritalStatusOther, setMaritalStatusOther] = useState("");
  const [accomplishedEducation, setAccomplishedEducation] = useState(0);
  const [accomplishedEducationOther, setAccomplishedEducationOther] = useState("");

  // Check authentication and load existing state
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    loadSpeakerState();
  }, [authManager, navigate]);

  const loadSpeakerState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE");
      if (existing) {
        const speakerState = JSON.parse(existing);

        setTags(speakerState.tags || []);
        setJoinDate(speakerState.joinDate || new Date().toISOString().split("T")[0]);
        setGender(speakerState.gender || 0);
        setGenderOther(speakerState.genderOther || "");
        setAdditionalComment(speakerState.additionalComment || "");
        setStatusInCountry(
          speakerState.statusInCountry !== undefined && speakerState.statusInCountry !== null
            ? parseInt(speakerState.statusInCountry)
            : 0
        );
        setStatusInCountryOther(speakerState.statusInCountryOther || "");
        setCountryOfOrigin(speakerState.countryOfOrigin || "");
        setDateOfEntryIntoCountry(speakerState.dateOfEntryIntoCountry || "");
        setMaritalStatus(
          speakerState.maritalStatus !== undefined && speakerState.maritalStatus !== null
            ? parseInt(speakerState.maritalStatus)
            : 0
        );
        setMaritalStatusOther(speakerState.maritalStatusOther || "");
        setAccomplishedEducation(
          speakerState.accomplishedEducation !== undefined && speakerState.accomplishedEducation !== null
            ? parseInt(speakerState.accomplishedEducation)
            : 0
        );
        setAccomplishedEducationOther(speakerState.accomplishedEducationOther || "");
      } else {
        navigate("/admin/speakers/add/step-1-search");
      }
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error loading speaker state:", error);
      }
      navigate("/admin/speakers/add/step-1-search");
    }
  }, [navigate]);

  const getExistingState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE");
      return existing ? JSON.parse(existing) : {};
    } catch (error) {
      return {};
    }
  }, []);

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

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

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

    let newErrors = {};
    let hasErrors = false;

    // Basic validation
    // Gender is optional, but if "Other" is selected, specify is required
    if (gender === SPEAKER_GENDER_OTHER && !genderOther.trim()) {
      newErrors.genderOther = "Please specify other gender";
      hasErrors = true;
    }

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

    // Job seeker validation logic kept for API compatibility
    if (isJobSeeker === SPEAKER_IS_JOB_SEEKER_YES) {
      if (statusInCountry === 0) {
        newErrors.statusInCountry = "Status in country is required";
        hasErrors = true;
      } else if (statusInCountry === SPEAKER_STATUS_IN_COUNTRY_OTHER && !statusInCountryOther.trim()) {
        newErrors.statusInCountryOther = "Please specify other status";
        hasErrors = true;
      }

      if (
        statusInCountry === SPEAKER_STATUS_IN_COUNTRY_PERMANENT_RESIDENT ||
        statusInCountry === SPEAKER_STATUS_IN_COUNTRY_NATURALIZED_CITIZEN ||
        statusInCountry === SPEAKER_STATUS_IN_COUNTRY_PROTECTED_PERSON
      ) {
        if (!countryOfOrigin || countryOfOrigin === "") {
          newErrors.countryOfOrigin = "Country of origin is required";
          hasErrors = true;
        }
        if (!dateOfEntryIntoCountry) {
          newErrors.dateOfEntryIntoCountry = "Date of entry into country is required";
          hasErrors = true;
        }
      }

      if (maritalStatus === 0) {
        newErrors.maritalStatus = "Marital status is required";
        hasErrors = true;
      } else if (maritalStatus === SPEAKER_MARITAL_STATUS_OTHER && !maritalStatusOther.trim()) {
        newErrors.maritalStatusOther = "Please specify other marital status";
        hasErrors = true;
      }

      if (accomplishedEducation === 0) {
        newErrors.accomplishedEducation = "Education level is required";
        hasErrors = true;
      } else if (accomplishedEducation === SPEAKER_EDUCATION_OTHER && !accomplishedEducationOther.trim()) {
        newErrors.accomplishedEducationOther = "Please specify other education level";
        hasErrors = true;
      }
    }

    if (hasErrors) {
      setErrors(newErrors);
      return;
    }

    // Save to session storage
    const existingState = getExistingState();
    // Remove fields that are no longer used
    delete existingState.birthDate;
    delete existingState.howDidYouHearAboutUsID;
    delete existingState.isHowDidYouHearAboutUsOther;
    delete existingState.howDidYouHearAboutUsOther;

    const speakerState = {
      ...existingState,
      isJobSeeker,
      tags,
      joinDate,
      gender,
      genderOther,
      additionalComment,
      statusInCountry,
      statusInCountryOther,
      countryOfOrigin,
      dateOfEntryIntoCountry,
      maritalStatus,
      maritalStatusOther,
      accomplishedEducation,
      accomplishedEducationOther,
    };

    try {
      sessionStorage.setItem("FLASHPOINTTRAINING_SPEAKER_CREATION_STATE", JSON.stringify(speakerState));
      navigate("/admin/speakers/add/step-7");
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Error saving speaker state:", error);
      }
      setErrors({ general: "Failed to save data. Please try again." });
    }
  }, [
    gender,
    genderOther,
    joinDate,
    isJobSeeker,
    tags,
    additionalComment,
    statusInCountry,
    statusInCountryOther,
    countryOfOrigin,
    dateOfEntryIntoCountry,
    maritalStatus,
    maritalStatusOther,
    accomplishedEducation,
    accomplishedEducationOther,
    getExistingState,
    navigate,
  ]);

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={6}
        title="Add New Speaker"
        subtitle="Provide metrics and demographic information for the speaker"
        icon={ChatBubbleBottomCenterIcon}
      >
        <form onSubmit={onSubmitClick}>
          {/* Error Alert */}
          {errors.general && (
            <Alert
              type="error"
              message={errors.general}
              onClose={() => setErrors({})}
              className="mb-6"
            />
          )}

          {/* Personal Information Section */}
          <FormCard
            title="Personal Information"
            icon={UserIcon}
            description="Demographic and personal details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              {/* Tags */}
              <FormRow columns={1}>
                <TagsMultiSelect
                  id="tags"
                  name="tags"
                  label="Tags (Optional)"
                  value={tags}
                  onChange={setTags}
                  error={errors.tags}
                  required={false}
                  helperText="Select tags to categorize this speaker"
                  onUnauthorized={onUnauthorized}
                />
              </FormRow>

              {/* Gender and Join Date */}
              <FormRow columns={2}>
                <Select
                  label="Gender"
                  name="gender"
                  value={String(gender)}
                  onChange={(value) => setGender(parseInt(value))}
                  options={GENDER_OPTIONS}
                  icon={UserIcon}
                  placeholder=""
                  required={false}
                  error={errors.gender}
                />
                <Input
                  label="Join Date"
                  name="joinDate"
                  type="date"
                  value={joinDate}
                  onChange={(value) => setJoinDate(value)}
                  icon={CalendarIcon}
                  required
                  error={errors.joinDate}
                  helperText="The date this speaker joined the organization (defaults to today's date)"
                />
              </FormRow>

              {gender === SPEAKER_GENDER_OTHER && (
                <FormRow columns={1}>
                  <Input
                    label="Gender (Other)"
                    name="genderOther"
                    value={genderOther}
                    onChange={(value) => setGenderOther(value)}
                    placeholder="Please specify"
                    required
                    error={errors.genderOther}
                  />
                </FormRow>
              )}

              {/* Additional Comments */}
              <FormRow columns={1}>
                <Textarea
                  id="additionalComment"
                  label="Additional Comment (Optional)"
                  name="additionalComment"
                  value={additionalComment}
                  onChange={(value) => setAdditionalComment(value)}
                  placeholder="Enter any additional comments or notes about this speaker"
                  rows={4}
                  helperText={`${additionalComment.length}/638 characters`}
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Form Actions */}
          <div className="flex flex-col sm:flex-row gap-3 mt-6">
            <Button
              type="button"
              variant="outline"
              onClick={handleBack}
              icon={ArrowLeftIcon}
              className="flex-1"
            >
              Back
            </Button>
            <Button
              type="submit"
              variant="primary"
              icon={ArrowRightIcon}
              disabled={isLoading}
              loading={isLoading}
              className="flex-1"
            >
              Next
            </Button>
          </div>
        </form>
      </StepWizard>
    </UIXThemeProvider>
  );
}

export default AdminSpeakerAddStep6Page;
