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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  WrenchScrewdriverIcon,
  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 {
  FACILITATOR_GENDER_OTHER,
  FACILITATOR_GENDER_MALE,
  FACILITATOR_GENDER_FEMALE,
  FACILITATOR_GENDER_PREFER_NOT_TO_SAY,
} from "../../../../constants/Facilitator";

// 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(FACILITATOR_GENDER_MALE), label: "Male" },
  { value: String(FACILITATOR_GENDER_FEMALE), label: "Female" },
  { value: String(FACILITATOR_GENDER_OTHER), label: "Other" },
  { value: String(FACILITATOR_GENDER_PREFER_NOT_TO_SAY), label: "Prefer not to say" },
];


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

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

  // Metrics form data
  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("");

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

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

  const loadFacilitatorState = useCallback(() => {
    try {
      const existing = sessionStorage.getItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE");
      if (existing) {
        const facilitatorState = JSON.parse(existing);

        setTags(facilitatorState.tags || []);
        setJoinDate(facilitatorState.joinDate || new Date().toISOString().split("T")[0]);
        setGender(facilitatorState.gender || 0);
        setGenderOther(facilitatorState.genderOther || "");
        setAdditionalComment(facilitatorState.additionalComment || "");
      } else {
        navigate("/admin/facilitators/add/step-1-search");
      }
    } catch (error) {
      console.error("Error loading facilitator state:", error);
      navigate("/admin/facilitators/add/step-1-search");
    }
  }, [navigate]);

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

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

  const handleBack = useCallback(() => {
    navigate("/admin/facilitators/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 === FACILITATOR_GENDER_OTHER && !genderOther.trim()) {
      newErrors.genderOther = "Please specify other gender";
      hasErrors = true;
    }

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

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

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

    const facilitatorState = {
      ...existingState,
      tags,
      joinDate,
      gender,
      genderOther,
      additionalComment,
    };

    try {
      sessionStorage.setItem("FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE", JSON.stringify(facilitatorState));
      navigate("/admin/facilitators/add/step-7");
    } catch (error) {
      console.error("Error saving facilitator state:", error);
      setErrors({ general: "Failed to save data. Please try again." });
    }
  }, [
    gender,
    genderOther,
    joinDate,
    tags,
    additionalComment,
    getExistingState,
    navigate,
  ]);

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={6}
        title="Add New Facilitator"
        subtitle="Provide metrics and demographic information for the facilitator"
        icon={WrenchScrewdriverIcon}
      >
        <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 facilitator"
                  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 facilitator joined the organization (defaults to today's date)"
                />
              </FormRow>

              {gender === FACILITATOR_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 facilitator"
                  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 AdminFacilitatorAddStep6Page;
