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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate } from "react-router";
import { useAuthManager } from "../../../../services/Services";
import {
  WrenchScrewdriverIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  BuildingOfficeIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Button,
  Alert,
} from "../../../../components/UIX";

// Constants
const INDIVIDUAL_FACILITATOR_TYPE_OF_ID = 1;
const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;
const FACILITATOR_PHONE_TYPE_WORK = 2;

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

// Organization type options - moved outside component
const ORGANIZATION_TYPE_OPTIONS = [
  { value: "0", label: "Please select" },
  { value: "1", label: "Corporation" },
  { value: "2", label: "Social Enterprise" },
  { value: "3", label: "Sole Proprietorship" },
  { value: "4", label: "LLC" },
];

// Phone type options - moved outside component
const PHONE_TYPE_OPTIONS = [
  { value: "0", label: "Please select" },
  { value: "1", label: "Mobile" },
  { value: "2", label: "Work" },
  { value: "3", label: "Home" },
];

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

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

  // Form data
  const [facilitatorType, setFacilitatorType] = useState(null);
  const [representitiveOrganizationName, setRepresentitiveOrganizationName] = useState("");
  const [representitiveOrganizationType, setRepresentitiveOrganizationType] = useState(0);
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [phoneType, setPhoneType] = useState(1);
  const [phoneExtension, setPhoneExtension] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [otherPhone, setOtherPhone] = useState("");
  const [otherPhoneType, setOtherPhoneType] = useState(0);
  const [otherPhoneExtension, setOtherPhoneExtension] = useState("");
  const [isOkToText, setIsOkToText] = useState(true);
  const [isOkToEmail, setIsOkToEmail] = useState(true);

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

    // Load existing facilitator creation state
    loadFacilitatorState();
  }, [authManager, navigate]);

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

        setFacilitatorType(facilitatorState.type || null);
        setRepresentitiveOrganizationName(facilitatorState.representitiveOrganizationName || "");
        setRepresentitiveOrganizationType(facilitatorState.representitiveOrganizationType || 0);
        setEmail(facilitatorState.email || "");
        setPhone(facilitatorState.phone || "");
        setPhoneType(facilitatorState.phoneType || 1);
        setPhoneExtension(facilitatorState.phoneExtension || "");
        setFirstName(facilitatorState.firstName || "");
        setLastName(facilitatorState.lastName || "");
        setOtherPhone(facilitatorState.otherPhone || "");
        setOtherPhoneType(facilitatorState.otherPhoneType || 0);
        setOtherPhoneExtension(facilitatorState.otherPhoneExtension || "");
        setIsOkToText(
          facilitatorState.isOkToText !== undefined
            ? facilitatorState.isOkToText
            : true,
        );
        setIsOkToEmail(
          facilitatorState.isOkToEmail !== undefined
            ? facilitatorState.isOkToEmail
            : true,
        );
      } else {
        // No state found, redirect back to step 2
        navigate("/admin/facilitators/add/step-2");
      }
    } catch (error) {
      console.error("Error loading facilitator state:", error);
      navigate("/admin/facilitators/add/step-2");
    }
  }, [navigate]);

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

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

    let newErrors = {};
    let hasErrors = false;

    // Validation for representative facilitators
    if (facilitatorType === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID) {
      if (!representitiveOrganizationName.trim()) {
        newErrors.representitiveOrganizationName = "Organization name is required";
        hasErrors = true;
      }
      if (representitiveOrganizationType === 0) {
        newErrors.representitiveOrganizationType = "Organization type is required";
        hasErrors = true;
      }
    }

    // General validation
    if (!firstName.trim()) {
      newErrors.firstName = "First name is required";
      hasErrors = true;
    }
    if (!lastName.trim()) {
      newErrors.lastName = "Last name is required";
      hasErrors = true;
    }
    if (!email.trim()) {
      newErrors.email = "Email is required";
      hasErrors = true;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      newErrors.email = "Please enter a valid email address";
      hasErrors = true;
    }
    if (!phone.trim()) {
      newErrors.phone = "Phone number is required";
      hasErrors = true;
    }
    if (phoneType === 0) {
      newErrors.phoneType = "Phone type is required";
      hasErrors = true;
    }

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

    // Save to session storage
    const facilitatorState = {
      // Keep any existing data from previous steps
      ...getExistingState(),
      // Then override with current form values
      type: facilitatorType,
      representitiveOrganizationName,
      representitiveOrganizationType,
      firstName,
      lastName,
      email,
      phone,
      phoneType,
      phoneExtension,
      otherPhone,
      otherPhoneType,
      otherPhoneExtension,
      isOkToText,
      isOkToEmail,
    };

    try {
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE",
        JSON.stringify(facilitatorState),
      );
      navigate("/admin/facilitators/add/step-4");
    } catch (error) {
      console.error("Error saving facilitator state:", error);
      setErrors({ general: "Failed to save data. Please try again." });
    }
  }, [facilitatorType, representitiveOrganizationName, representitiveOrganizationType, firstName, lastName, email, phone, phoneType, phoneExtension, otherPhone, otherPhoneType, otherPhoneExtension, isOkToText, isOkToEmail, getExistingState, navigate]);

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

  if (facilitatorType === null) {
    return (
      <UIXThemeProvider>
        <div className="min-h-screen flex items-center justify-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-current opacity-25"></div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={3}
        title="Add New Facilitator"
        subtitle="Enter contact information for the new facilitator"
        icon={WrenchScrewdriverIcon}
      >
        <form onSubmit={onSubmitClick}>
          {/* Error Alert */}
          {errors.general && (
            <Alert
              type="error"
              message={errors.general}
              onClose={() => setErrors({})}
              className="mb-6"
            />
          )}

          {/* Representative Facilitator Section */}
          {facilitatorType === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID && (
            <FormCard
              title="Business Information"
              icon={BuildingOfficeIcon}
              description="Representative facilitator details"
              maxWidth="full"
              className="mb-6"
            >
              <FormSection>
                <FormRow columns={1}>
                  <Input
                    label="Business Name"
                    name="representitiveOrganizationName"
                    value={representitiveOrganizationName}
                    onChange={(value) => setRepresentitiveOrganizationName(value)}
                    placeholder="Enter business name"
                    icon={BuildingOfficeIcon}
                    required
                    error={errors.representitiveOrganizationName}
                  />
                </FormRow>

                <FormRow columns={1}>
                  <Select
                    label="Business Type"
                    name="representitiveOrganizationType"
                    value={String(representitiveOrganizationType)}
                    onChange={(value) => setRepresentitiveOrganizationType(parseInt(value))}
                    options={ORGANIZATION_TYPE_OPTIONS}
                    icon={BuildingOfficeIcon}
                    placeholder=""
                    required
                    error={errors.representitiveOrganizationType}
                  />
                </FormRow>
              </FormSection>
            </FormCard>
          )}

          {/* Facilitator Information Section */}
          <FormCard
            title="Facilitator Information"
            icon={UserIcon}
            description="Facilitator contact details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="First Name"
                  name="firstName"
                  value={firstName}
                  onChange={(value) => setFirstName(value)}
                  placeholder="Enter first name"
                  icon={UserIcon}
                  autoComplete="off"
                  required
                  error={errors.firstName}
                />
                <Input
                  label="Last Name"
                  name="lastName"
                  value={lastName}
                  onChange={(value) => setLastName(value)}
                  placeholder="Enter last name"
                  icon={UserIcon}
                  autoComplete="off"
                  required
                  error={errors.lastName}
                />
              </FormRow>

              <FormRow columns={1}>
                <Input
                  label="Email Address"
                  name="email"
                  type="email"
                  value={email}
                  onChange={(value) => setEmail(value)}
                  placeholder="Enter email address"
                  icon={EnvelopeIcon}
                  autoComplete="off"
                  required
                  error={errors.email}
                />
              </FormRow>

              <FormRow columns={1}>
                <Checkbox
                  id="isOkToEmail"
                  label="I agree to receive electronic email"
                  checked={isOkToEmail}
                  onChange={(e) => setIsOkToEmail(e.target.checked)}
                />
              </FormRow>

              <FormRow columns={2}>
                <Input
                  label="Phone Number"
                  name="phone"
                  type="tel"
                  value={phone}
                  onChange={(value) => setPhone(value)}
                  placeholder="Enter phone number"
                  icon={PhoneIcon}
                  autoComplete="off"
                  required
                  error={errors.phone}
                />
                <Select
                  label="Phone Type"
                  name="phoneType"
                  value={String(phoneType)}
                  onChange={(value) => setPhoneType(parseInt(value))}
                  options={PHONE_TYPE_OPTIONS}
                  icon={PhoneIcon}
                  placeholder=""
                  required
                  error={errors.phoneType}
                />
              </FormRow>

              {phoneType === FACILITATOR_PHONE_TYPE_WORK && (
                <FormRow columns={1}>
                  <Input
                    label="Phone Extension (Optional)"
                    name="phoneExtension"
                    value={phoneExtension}
                    onChange={(value) => setPhoneExtension(value)}
                    placeholder="Enter extension"
                  />
                </FormRow>
              )}

              <FormRow columns={1}>
                <Checkbox
                  id="isOkToText"
                  label="I agree to receive texts to my phone"
                  checked={isOkToText}
                  onChange={(e) => setIsOkToText(e.target.checked)}
                />
              </FormRow>

              <FormRow columns={2}>
                <Input
                  label="Other Phone Number"
                  name="otherPhone"
                  type="tel"
                  value={otherPhone}
                  onChange={(value) => setOtherPhone(value)}
                  placeholder="Enter other phone number"
                  icon={PhoneIcon}
                />
                {otherPhone && (
                  <Select
                    label="Other Phone Type"
                    name="otherPhoneType"
                    value={String(otherPhoneType)}
                    onChange={(value) => setOtherPhoneType(parseInt(value))}
                    options={PHONE_TYPE_OPTIONS}
                    icon={PhoneIcon}
                    placeholder=""
                  />
                )}
              </FormRow>

              {otherPhoneType === FACILITATOR_PHONE_TYPE_WORK && otherPhone && (
                <FormRow columns={1}>
                  <Input
                    label="Other Phone Extension (Optional)"
                    name="otherPhoneExtension"
                    value={otherPhoneExtension}
                    onChange={(value) => setOtherPhoneExtension(value)}
                    placeholder="Enter extension"
                  />
                </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 AdminFacilitatorAddStep3Page;
