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

import React, { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate } from "react-router";
import { useAuthManager, useInsuranceRequirementManager, useServiceFeeManager, useSpecializationManager, useCertificationManager } from "../../../../services/Services";
import {
  WrenchScrewdriverIcon,
  ArrowLeftIcon,
  ArrowRightIcon,
  ChartBarIcon,
  AcademicCapIcon,
  ShieldCheckIcon,
  CurrencyDollarIcon,
  CalendarDaysIcon,
  IdentificationIcon,
  UserGroupIcon,
  ComputerDesktopIcon,
  LockClosedIcon,
  PhoneIcon,
  LanguageIcon,
  ClockIcon,
  PlusIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import {
  UIXThemeProvider,
  StepWizard,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Button,
  Alert,
} from "../../../../components/UIX";
import {
  SkillSetsMultiSelect,
  SpecializationCertificationPicker,
} from "../../../../components/business/selects";
import { FACILITATOR_LEVEL_OPTIONS } from "../../../../constants/Facilitator";

// Constants - 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: false },
  { title: "Metrics" },
  { title: "Review" },
];

const LANGUAGE_OPTIONS = [
  { value: "English", label: "English" },
  { value: "French", label: "French" },
];

const DAYS_OF_WEEK = [
  { key: "monday", label: "Monday" },
  { key: "tuesday", label: "Tuesday" },
  { key: "wednesday", label: "Wednesday" },
  { key: "thursday", label: "Thursday" },
  { key: "friday", label: "Friday" },
  { key: "saturday", label: "Saturday" },
  { key: "sunday", label: "Sunday" },
];

function AdminFacilitatorAddStep5Page() {
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const insuranceRequirementManager = useInsuranceRequirementManager();
  const serviceFeeManager = useServiceFeeManager();

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

  // Level state
  const [level, setLevel] = useState("");

  // Availability state
  const [availability, setAvailability] = useState({
    monday: { am: false, pm: false },
    tuesday: { am: false, pm: false },
    wednesday: { am: false, pm: false },
    thursday: { am: false, pm: false },
    friday: { am: false, pm: false },
    saturday: { am: false, pm: false },
    sunday: { am: false, pm: false },
  });

  // Account form data
  const [skillSets, setSkillSets] = useState([]);
  const [insuranceRequirements, setInsuranceRequirements] = useState([]);
  const [insuranceRequirementOptions, setInsuranceRequirementOptions] = useState([]);

  // Specializations & Certifications - using new SpecializationCertificationPicker
  const [specializationsAndCertifications, setSpecializationsAndCertifications] = useState({
    certificationIds: [],
    specializationIds: [],
    _items: [],
  });

  const [hourlySalaryDesired, setHourlySalaryDesired] = useState("");
  const [limitSpecial, setLimitSpecial] = useState("");
  const [commercialInsuranceExpiryDate, setCommercialInsuranceExpiryDate] = useState("");
  const [autoInsuranceExpiryDate, setAutoInsuranceExpiryDate] = useState("");
  const [wsibNumber, setWsibNumber] = useState("");
  const [wsibInsuranceDate, setWsibInsuranceDate] = useState("");
  const [policeCheck, setPoliceCheck] = useState("");
  const [taxId, setTaxId] = useState("");
  const [serviceFeeId, setServiceFeeId] = useState("");
  const [isServiceFeeOther, setIsServiceFeeOther] = useState(false);
  const [serviceFeeOther, setServiceFeeOther] = useState("");
  const [serviceFeeOptions, setServiceFeeOptions] = useState([]);
  const [emergencyContactName, setEmergencyContactName] = useState("");
  const [emergencyContactRelationship, setEmergencyContactRelationship] = useState("");
  const [emergencyContactTelephone, setEmergencyContactTelephone] = useState("");
  const [emergencyContactAlternativeTelephone, setEmergencyContactAlternativeTelephone] = useState("");
  const [description, setDescription] = useState("");
  const [preferredLanguage, setPreferredLanguage] = useState("English");
  const [password, setPassword] = useState("");
  const [passwordRepeated, setPasswordRepeated] = useState("");

  // Define onUnauthorized callback before using it in useEffects
  const onUnauthorized = useCallback(() => {
    navigate("/login?unauthorized=true");
  }, [navigate]);

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

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

  // Fetch insurance requirement options
  useEffect(() => {
    const fetchInsuranceRequirementOptions = async () => {
      try {
        const options = await insuranceRequirementManager.getInsuranceRequirementSelectOptions(
          onUnauthorized,
          false
        );

        if (options && options.length > 0) {
          const formattedOptions = options.map(opt => ({
            value: opt.value !== undefined ? String(opt.value) : String(opt.id),
            label: opt.label || opt.text || opt.name || `Insurance Requirement ${opt.id}`,
          }));

          setInsuranceRequirementOptions(formattedOptions);
          // Insurance requirement is now optional - no auto-selection
        }
      } catch (error) {
        console.error("Error fetching insurance requirement options:", error);
      }
    };

    if (insuranceRequirementOptions.length === 0) {
      fetchInsuranceRequirementOptions();
    }
  }, [insuranceRequirementOptions.length]);

  // Fetch service fee options
  useEffect(() => {
    const fetchServiceFeeOptions = async () => {
      try {
        const options = await serviceFeeManager.getServiceFeeSelectOptions(
          onUnauthorized
        );

        if (options && options.length > 0) {
          const formattedOptions = options.map(opt => ({
            value: opt.value !== undefined ? String(opt.value) : String(opt.id),
            label: opt.label || opt.title || opt.name || `Service Fee ${opt.id}`,
          }));

          setServiceFeeOptions(formattedOptions);

          // Auto-select first valid option if none selected (skip placeholder options with value "0" or "")
          if (!serviceFeeId || serviceFeeId === "" || serviceFeeId === "0" || serviceFeeId === 0) {
            const firstValidOption = formattedOptions.find(opt => opt.value && opt.value !== "0" && opt.value !== "");
            if (firstValidOption) {
              setServiceFeeId(firstValidOption.value);

              if (firstValidOption.label && firstValidOption.label.toLowerCase() === "other") {
                setIsServiceFeeOther(true);
              }
            }
          }
        }
      } catch (error) {
        console.error("Error fetching service fee options:", error);
      }
    };

    if (serviceFeeOptions.length === 0) {
      fetchServiceFeeOptions();
    }
  }, [serviceFeeId, serviceFeeOptions.length]);

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

        if (facilitatorState.level) setLevel(facilitatorState.level);
        if (facilitatorState.availability) setAvailability(facilitatorState.availability);

        setSkillSets(facilitatorState.skillSets || []);
        setInsuranceRequirements(facilitatorState.insuranceRequirements || []);

        // Load specializations and certifications
        setSpecializationsAndCertifications({
          certificationIds: facilitatorState.certificationIds || facilitatorState.certifications || [],
          specializationIds: facilitatorState.specializationIds || (facilitatorState.specializationId ? [facilitatorState.specializationId] : []),
          _items: facilitatorState.specializationCertificationItems || [],
        });

        setHourlySalaryDesired(facilitatorState.hourlySalaryDesired || "");
        setLimitSpecial(facilitatorState.limitSpecial || "");
        setCommercialInsuranceExpiryDate(facilitatorState.commercialInsuranceExpiryDate || "");
        setAutoInsuranceExpiryDate(facilitatorState.autoInsuranceExpiryDate || "");
        setWsibNumber(facilitatorState.wsibNumber || "");
        setWsibInsuranceDate(facilitatorState.wsibInsuranceDate || "");
        setPoliceCheck(facilitatorState.policeCheck || "");
        setTaxId(facilitatorState.taxId || "");
        setServiceFeeId(facilitatorState.serviceFeeId || "");
        setIsServiceFeeOther(facilitatorState.isServiceFeeOther || false);
        setServiceFeeOther(facilitatorState.serviceFeeOther || "");
        setEmergencyContactName(facilitatorState.emergencyContactName || "");
        setEmergencyContactRelationship(facilitatorState.emergencyContactRelationship || "");
        setEmergencyContactTelephone(facilitatorState.emergencyContactTelephone || "");
        setEmergencyContactAlternativeTelephone(facilitatorState.emergencyContactAlternativeTelephone || "");
        setDescription(facilitatorState.description || "");
        setPreferredLanguage(facilitatorState.preferredLanguage || "English");
        setPassword(facilitatorState.password || "");
        setPasswordRepeated(facilitatorState.passwordRepeated || "");
      } 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 handleAvailabilityChange = useCallback((day, period) => {
    setAvailability((prev) => ({
      ...prev,
      [day]: {
        ...prev[day],
        [period]: !prev[day][period],
      },
    }));

    setErrors((prevErrors) => {
      if (prevErrors.availability) {
        const { availability, ...newErrors } = prevErrors;
        return newErrors;
      }
      return prevErrors;
    });
  }, []);

  const hasAvailabilitySelected = useCallback(() => {
    return Object.values(availability).some((day) => day.am || day.pm);
  }, [availability]);

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

  const handleSpecializationsAndCertificationsChange = useCallback((value) => {
    setSpecializationsAndCertifications(value);

    // Clear error when user adds certifications
    if (value.certificationIds && value.certificationIds.length > 0) {
      setErrors(prev => {
        if (prev.certifications) {
          const { certifications, ...newErrors } = prev;
          return newErrors;
        }
        return prev;
      });
    }
  }, []);

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

    let newErrors = {};
    let hasErrors = false;

    if (!level) {
      newErrors.level = "Facilitator level is required";
      hasErrors = true;
    }

    if (!hasAvailabilitySelected()) {
      newErrors.availability = "At least one availability time slot must be selected";
      hasErrors = true;
    }

    // At least one skill set is required
    if (!skillSets || skillSets.length === 0) {
      newErrors.skillSets = "At least one skill set is required";
      hasErrors = true;
    }

    // At least one specialization and certification is required
    if (!specializationsAndCertifications.specializationIds || specializationsAndCertifications.specializationIds.length === 0) {
      newErrors.certifications = "At least one specialization is required";
      hasErrors = true;
    } else if (!specializationsAndCertifications.certificationIds || specializationsAndCertifications.certificationIds.length === 0) {
      newErrors.certifications = "At least one certification is required";
      hasErrors = true;
    }
    // Insurance requirement is now optional - no validation needed
    if (!hourlySalaryDesired || String(hourlySalaryDesired).trim() === "") {
      newErrors.hourlySalaryDesired = "Hourly rate is required";
      hasErrors = true;
    } else if (parseFloat(hourlySalaryDesired) < 0) {
      newErrors.hourlySalaryDesired = "Hourly rate cannot be negative";
      hasErrors = true;
    }
    if (!policeCheck.trim()) {
      newErrors.policeCheck = "Police check date is required";
      hasErrors = true;
    }
    // Commercial insurance expiry date is now optional
    // Check if serviceFeeId is a valid value (not empty, not "0", not 0)
    if (!serviceFeeId || serviceFeeId === "" || serviceFeeId === "0" || serviceFeeId === 0) {
      newErrors.serviceFeeId = "Service fee is required";
      hasErrors = true;
    }
    if (isServiceFeeOther && !serviceFeeOther.trim()) {
      newErrors.serviceFeeOther = "Please specify the custom service fee";
      hasErrors = true;
    }
    if (!preferredLanguage.trim()) {
      newErrors.preferredLanguage = "Preferred language is required";
      hasErrors = true;
    }

    if (password || passwordRepeated) {
      if (password !== passwordRepeated) {
        newErrors.password = "Passwords do not match";
        newErrors.passwordRepeated = "Passwords do not match";
        hasErrors = true;
      }
      if (password && password.length < 8) {
        newErrors.password = "Password must be at least 8 characters";
        hasErrors = true;
      }
    }

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

    const existingState = getExistingState();
    // Remove fields that are no longer used
    delete existingState.specializations;
    delete existingState.duesDate;
    delete existingState.driversLicenseClass;
    delete existingState.vehicleTypes;
    delete existingState.specializationId; // Old single specialization
    delete existingState.selectedCertifications; // Old certification format

    const facilitatorState = {
      ...existingState,
      level,
      availability,
      skillSets,
      insuranceRequirements,
      certificationIds: specializationsAndCertifications.certificationIds,
      specializationIds: specializationsAndCertifications.specializationIds,
      specializationCertificationItems: specializationsAndCertifications._items || [],
      certifications: specializationsAndCertifications.certificationIds, // For backward compatibility
      hourlySalaryDesired: hourlySalaryDesired ? parseInt(hourlySalaryDesired) : 0,
      limitSpecial,
      commercialInsuranceExpiryDate,
      autoInsuranceExpiryDate,
      wsibNumber,
      wsibInsuranceDate,
      policeCheck,
      taxId,
      serviceFeeId,
      isServiceFeeOther,
      serviceFeeOther,
      emergencyContactName,
      emergencyContactRelationship,
      emergencyContactTelephone,
      emergencyContactAlternativeTelephone,
      description,
      preferredLanguage,
      password,
      passwordRepeated,
    };

    try {
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_FACILITATOR_CREATION_STATE",
        JSON.stringify(facilitatorState),
      );
      navigate("/admin/facilitators/add/step-6");
    } catch (error) {
      console.error("Error saving facilitator state:", error);
      setErrors({ general: "Failed to save data. Please try again." });
    }
  };

  const handleServiceFeeChange = useCallback((value) => {
    setServiceFeeId(value);

    // Clear error when a valid value is selected
    if (value && value !== "" && value !== "0" && value !== 0) {
      setErrors((prevErrors) => {
        if (prevErrors.serviceFeeId) {
          const { serviceFeeId: _, ...newErrors } = prevErrors;
          return newErrors;
        }
        return prevErrors;
      });
    }

    // Check if "Other" was selected
    const selectedOption = serviceFeeOptions.find(opt => String(opt.value) === String(value));
    const isOther = selectedOption && selectedOption.label && selectedOption.label.toLowerCase() === "other";
    setIsServiceFeeOther(isOther);

    if (!isOther) {
      setServiceFeeOther("");
    }
  }, [serviceFeeOptions]);

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

  return (
    <UIXThemeProvider>
      <StepWizard
        steps={WIZARD_STEPS}
        currentStep={5}
        title="Add New Facilitator"
        subtitle="Configure account settings and preferences for the new facilitator"
        icon={WrenchScrewdriverIcon}
      >
        <form onSubmit={onSubmitClick}>
          {errors.general && (
            <Alert
              type="error"
              message={errors.general}
              onClose={() => setErrors({})}
              className="mb-6"
            />
          )}

          {/* Level Section */}
          <FormCard
            title="Level"
            icon={ChartBarIcon}
            description="Select the facilitator's level classification"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Facilitator Level"
                  name="level"
                  value={level}
                  onChange={(value) => {
                    setLevel(value);
                    if (errors.level) {
                      setErrors({ ...errors, level: null });
                    }
                  }}
                  options={FACILITATOR_LEVEL_OPTIONS}
                  placeholder=""
                  required
                  error={errors.level}
                  helperText="Select the facilitator's current level: Level 1 (in training), Level 2 (secondary), Level 3 (lead), or Level 4 (trainer)"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Availability Section */}
          <FormCard
            title="Availability"
            icon={ClockIcon}
            description="Select the time slots when the facilitator is available"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-6 py-4 text-left text-base font-medium text-gray-500 uppercase">Day</th>
                      <th className="px-6 py-4 text-center text-base font-medium text-gray-500 uppercase">AM</th>
                      <th className="px-6 py-4 text-center text-base font-medium text-gray-500 uppercase">PM</th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {DAYS_OF_WEEK.map((day) => (
                      <tr key={day.key} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap text-base font-medium text-gray-900">
                          {day.label}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-center">
                          <input
                            id={`availability-${day.key}-am`}
                            name={`availability-${day.key}-am`}
                            type="checkbox"
                            checked={availability[day.key].am}
                            onChange={() => handleAvailabilityChange(day.key, "am")}
                            className="h-5 w-5 text-blue-600 focus:ring-blue-500 border-gray-300 rounded cursor-pointer"
                          />
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-center">
                          <input
                            id={`availability-${day.key}-pm`}
                            name={`availability-${day.key}-pm`}
                            type="checkbox"
                            checked={availability[day.key].pm}
                            onChange={() => handleAvailabilityChange(day.key, "pm")}
                            className="h-5 w-5 text-blue-600 focus:ring-blue-500 border-gray-300 rounded cursor-pointer"
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {errors.availability && (
                <p className="mt-2 text-sm text-red-600">{errors.availability}</p>
              )}
              <p className="mt-3 text-base opacity-60">
                <span className="font-medium">Note:</span> At least one time slot must be selected.
              </p>
            </FormSection>
          </FormCard>

          {/* Skill Sets Section */}
          <FormCard
            title="Skill Sets"
            icon={AcademicCapIcon}
            description="Select all skill sets that apply to this facilitator"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              {/* Honeypot for Chrome autofill - prevents autofill in skill sets field */}
              <input
                id="organization_honeypot"
                name="organization_honeypot"
                type="text"
                autoComplete="organization"
                tabIndex={-1}
                aria-label="Organization honeypot - do not fill"
                style={{
                  position: 'absolute',
                  left: '-9999px',
                  width: '1px',
                  height: '1px',
                  opacity: 0,
                  pointerEvents: 'none'
                }}
              />
              <SkillSetsMultiSelect
                value={skillSets}
                onChange={(value) => {
                  setSkillSets(value);
                  if (errors.skillSets && value && value.length > 0) {
                    const { skillSets: _, ...newErrors } = errors;
                    setErrors(newErrors);
                  }
                }}
                error={errors.skillSets}
                required={true}
                helperText="Choose the skills and expertise areas"
                onUnauthorized={onUnauthorized}
              />
            </FormSection>
          </FormCard>

          {/* Specializations & Certifications Section */}
          <FormCard
            title="Specializations & Certifications"
            icon={AcademicCapIcon}
            description="Professional specializations and certifications"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <SpecializationCertificationPicker
                id="specializations-certifications"
                value={specializationsAndCertifications}
                onChange={handleSpecializationsAndCertificationsChange}
                error={errors.certifications}
                required={true}
                label="Facilitator Specializations & Certifications"
                helperText="Add specializations and their associated certifications"
                onUnauthorized={onUnauthorized}
              />
            </FormSection>
          </FormCard>

          {/* Insurance Requirements Section */}
          <FormCard
            title="Insurance Requirements"
            icon={ShieldCheckIcon}
            description="Select insurance requirement for this facilitator"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Insurance Requirement (Optional)"
                  name="insuranceRequirement"
                  value={insuranceRequirements[0] || ""}
                  onChange={(value) => setInsuranceRequirements([value])}
                  options={insuranceRequirementOptions}
                  placeholder="Select insurance requirement"
                  required={false}
                  error={errors.insuranceRequirements}
                  helperText="Choose applicable insurance coverage type if required"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Financial Information */}
          <FormCard
            title="Financial Information"
            icon={CurrencyDollarIcon}
            description="Configure rates, fees, and financial details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="Hourly Rate"
                  name="hourlySalaryDesired"
                  type="number"
                  value={hourlySalaryDesired}
                  onChange={(value) => setHourlySalaryDesired(value)}
                  placeholder="$ / hr"
                  icon={CurrencyDollarIcon}
                  required
                  error={errors.hourlySalaryDesired}
                />
                <Select
                  label="Service Fee"
                  name="serviceFeeId"
                  value={serviceFeeId}
                  onChange={(value) => handleServiceFeeChange(value)}
                  options={serviceFeeOptions}
                  placeholder=""
                  required
                  error={errors.serviceFeeId}
                  helperText="Select the applicable service fee"
                />
              </FormRow>

              {isServiceFeeOther && (
                <FormRow columns={1}>
                  <Input
                    label="Specify Other Service Fee"
                    name="serviceFeeOther"
                    value={serviceFeeOther}
                    onChange={(value) => setServiceFeeOther(value)}
                    placeholder="Enter custom service fee details"
                    required
                    error={errors.serviceFeeOther}
                  />
                </FormRow>
              )}

              {/* Honeypot for Chrome autofill - prevents email autofill in HST field */}
              <input
                id="email_honeypot"
                name="email_honeypot"
                type="email"
                autoComplete="email"
                tabIndex={-1}
                aria-label="Email honeypot - do not fill"
                style={{
                  position: 'absolute',
                  left: '-9999px',
                  width: '1px',
                  height: '1px',
                  opacity: 0,
                  pointerEvents: 'none'
                }}
              />

              <FormRow columns={1}>
                <Input
                  label="HST # (Optional)"
                  name="taxId"
                  value={taxId}
                  onChange={(value) => setTaxId(value)}
                  placeholder="Enter HST number"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Important Dates */}
          <FormCard
            title="Important Dates"
            icon={CalendarDaysIcon}
            description="Track expiry dates and renewal schedules"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={2}>
                <Input
                  label="Police Check Expiry"
                  name="policeCheck"
                  type="date"
                  value={policeCheck}
                  onChange={(value) => setPoliceCheck(value)}
                  required
                  error={errors.policeCheck}
                />
                <Input
                  label="Commercial Insurance Expiry (Optional)"
                  name="commercialInsuranceExpiryDate"
                  type="date"
                  value={commercialInsuranceExpiryDate}
                  onChange={(value) => setCommercialInsuranceExpiryDate(value)}
                  required={false}
                  error={errors.commercialInsuranceExpiryDate}
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* Login Credentials */}
          <FormCard
            title="Login Credentials"
            icon={LockClosedIcon}
            description="Set up authentication for the facilitator's account"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              {/* Honeypot for Chrome autofill - positioned outside FormRow */}
              <input
                id="password_honeypot"
                name="password_honeypot"
                type="password"
                autoComplete="current-password"
                tabIndex={-1}
                aria-label="Password honeypot - do not fill"
                style={{
                  position: 'absolute',
                  left: '-9999px',
                  width: '1px',
                  height: '1px',
                  opacity: 0,
                  pointerEvents: 'none'
                }}
              />
              <FormRow columns={2}>
                <Input
                  label="Password (Optional)"
                  name="password"
                  type="password"
                  value={password}
                  onChange={(value) => setPassword(value)}
                  placeholder="Enter password (min 8 characters)"
                  icon={LockClosedIcon}
                  autoComplete="new-password"
                  error={errors.password}
                  helperText="Leave blank to auto-generate a password"
                />
                <Input
                  label="Confirm Password (Optional)"
                  name="passwordRepeated"
                  type="password"
                  value={passwordRepeated}
                  onChange={(value) => setPasswordRepeated(value)}
                  placeholder="Repeat password"
                  icon={LockClosedIcon}
                  autoComplete="new-password"
                  error={errors.passwordRepeated}
                  helperText="Must match the password above if entered"
                />
              </FormRow>
            </FormSection>
          </FormCard>

          {/* System Settings */}
          <FormCard
            title="System Settings"
            icon={ComputerDesktopIcon}
            description="Language preferences and system configuration"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <Select
                  label="Preferred Language"
                  name="preferredLanguage"
                  value={preferredLanguage}
                  onChange={(value) => setPreferredLanguage(value)}
                  options={LANGUAGE_OPTIONS}
                  icon={LanguageIcon}
                  placeholder=""
                  required
                  error={errors.preferredLanguage}
                />
              </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 AdminFacilitatorAddStep5Page;
