// File Path: monorepo/web/frontend/src/pages/Admin/Facilitator/Update/Page.jsx

import React, { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  ChevronLeftIcon,
  CheckCircleIcon,
  XCircleIcon,
  ExclamationTriangleIcon,
  BuildingOfficeIcon,
  HomeIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  BriefcaseIcon,
  ShieldCheckIcon,
  CurrencyDollarIcon,
  CalendarIcon,
  DocumentTextIcon,
  TruckIcon,
  ExclamationCircleIcon,
  HeartIcon,
  ChartPieIcon,
  ComputerDesktopIcon,
  GlobeAltIcon,
  ClipboardDocumentListIcon,
  EllipsisHorizontalIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  ArchiveBoxIcon,
  NoSymbolIcon,
  ClockIcon,
  PlusIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import {
  useFacilitatorManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  SkillSetsMultiSelect,
  InsuranceRequirementsMultiSelect,
  ServiceFeeSelect,
  TagsMultiSelect,
  SpecializationCertificationPicker,
} from "../../../../components/business/selects";
import {
  UIXThemeProvider,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Textarea,
  Button,
  Alert,
  Breadcrumb,
  Tabs,
  Spinner,
  useUIXTheme,
} from "../../../../components/UIX";

// Constants

// Facilitator level constants - matching backend integer values
const FACILITATOR_LEVEL_IN_TRAINING = 1;
const FACILITATOR_LEVEL_SECONDARY_FACILITATOR = 2;
const FACILITATOR_LEVEL_LEAD_FACILITATOR = 3;
const FACILITATOR_LEVEL_TRAINER = 4;

// Level options to use integer values
const FACILITATOR_LEVEL_OPTIONS = [
  { value: "", label: "Select a level" },
  { value: FACILITATOR_LEVEL_IN_TRAINING, label: "Level 1 (in training)" },
  {
    value: FACILITATOR_LEVEL_SECONDARY_FACILITATOR,
    label: "Level 2 (secondary facilitator)",
  },
  {
    value: FACILITATOR_LEVEL_LEAD_FACILITATOR,
    label: "Level 3 (lead facilitator)",
  },
  {
    value: FACILITATOR_LEVEL_TRAINER,
    label: "Level 4 (trainer)",
  },
];

const FACILITATOR_TYPE_OPTIONS = [
  { value: "1", label: "Individual" },
  { value: "2", label: "Representative" },
];

const ORGANIZATION_TYPE_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Educational" },
  { value: 2, label: "Private/Corporation" },
  { value: 3, label: "Non-profit" },
  { value: 4, label: "Government" },
];

const PHONE_TYPE_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Mobile" },
  { value: 2, label: "Work" },
  { value: 3, label: "Home" },
];

const GENDER_OPTIONS = [
  { value: 0, label: "Please select" },
  { value: 1, label: "Other" },
  { value: 2, label: "Male" },
  { value: 3, label: "Female" },
  { value: 4, label: "Transgender" },
  { value: 5, label: "Non-Binary" },
  { value: 6, label: "Two Spirit" },
  { value: 7, label: "Prefer not to say" },
  { value: 8, label: "Do not know" },
];

const JOB_SEEKER_OPTIONS = [
  { value: 1, label: "Yes" },
  { value: 2, label: "No" },
];

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

const REGION_OPTIONS = [
  { value: "", label: "Please select" },
  { value: "Alberta", label: "Alberta" },
  { value: "British Columbia", label: "British Columbia" },
  { value: "Manitoba", label: "Manitoba" },
  { value: "New Brunswick", label: "New Brunswick" },
  { value: "Newfoundland and Labrador", label: "Newfoundland and Labrador" },
  { value: "Northwest Territories", label: "Northwest Territories" },
  { value: "Nova Scotia", label: "Nova Scotia" },
  { value: "Nunavut", label: "Nunavut" },
  { value: "Ontario", label: "Ontario" },
  { value: "Prince Edward Island", label: "Prince Edward Island" },
  { value: "Quebec", label: "Quebec" },
  { value: "Saskatchewan", label: "Saskatchewan" },
  { value: "Yukon", label: "Yukon" },
];

// Helper function to format errors for display
const formatErrorsForAlert = (errors) => {
  if (!errors || typeof errors !== "object") {
    return null;
  }

  const errorList = [];
  for (const [field, message] of Object.entries(errors)) {
    if (message && field !== "general") {
      const fieldName = field
        .replace(/([A-Z])/g, " $1")
        .replace(/^./, (str) => str.toUpperCase())
        .trim();
      errorList.push(`• ${fieldName}: ${message}`);
    }
  }

  return errorList.length > 0 ? errorList : null;
};

function AdminFacilitatorUpdatePage() {
  const { aid } = useParams();
  const navigate = useNavigate();
  const facilitatorManager = useFacilitatorManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // Loading and error states
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [errors, setErrors] = useState({});
  const [alert, setAlert] = useState(null);
  const [facilitator, setFacilitator] = useState(null);

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

  // Facilitator data state - Complete fields based on backend requirements
  const [facilitatorData, setFacilitatorData] = useState({
    // Basic info
    type: "1",
    representitiveOrganizationName: "",
    representitiveOrganizationType: 0,
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    phoneType: 0,
    phoneExtension: "",
    otherPhone: "",
    otherPhoneType: 0,
    otherPhoneExtension: "",
    isOkToText: false,
    isOkToEmail: false,

    // Address
    country: "Canada",
    region: "",
    city: "",
    addressLine1: "",
    addressLine2: "",
    postalCode: "",
    hasShippingAddress: false,
    shippingName: "",
    shippingPhone: "",
    shippingCountry: "Canada",
    shippingRegion: "",
    shippingCity: "",
    shippingAddressLine1: "",
    shippingAddressLine2: "",
    shippingPostalCode: "",

    // Professional info
    skillSets: [],
    insuranceRequirements: [],
    vehicleTypes: [],
    certifications: [],
    serviceFeeId: "",
    hourlySalaryDesired: 0,
    limitSpecial: "",
    commercialInsuranceExpiryDate: "",
    autoInsuranceExpiryDate: "",
    wsibNumber: "",
    wsibInsuranceDate: "",
    policeCheck: "",
    taxId: "",
    driversLicenseClass: "",

    // Emergency contact
    emergencyContactName: "",
    emergencyContactRelationship: "",
    emergencyContactTelephone: "",
    emergencyContactAlternativeTelephone: "",

    // Metrics
    tags: [],
    howDidYouHearAboutUsID: "",
    isHowDidYouHearAboutUsOther: false,
    howDidYouHearAboutUsOther: "",
    gender: 0,
    genderOther: "",
    birthDate: "",
    joinDate: "",
    additionalComment: "",
    identifyAs: [],

    // Job seeker info
    isJobSeeker: 2,
    statusInCountry: 0,
    statusInCountryOther: "",
    countryOfOrigin: "",
    dateOfEntryIntoCountry: "",
    maritalStatus: 0,
    maritalStatusOther: "",
    accomplishedEducation: 0,
    accomplishedEducationOther: "",

    // Level/Avail.
    level: "",
    availability: {
      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 },
    },

    // System
    description: "",
    preferredLanguage: "English",
  });

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

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

  useEffect(() => {
    let mounted = true;

    const fetchFacilitatorDetail = () => {
      if (!aid) {
        setAlert({ type: "error", message: "Invalid facilitator ID" });
        setIsLoading(false);
        return;
      }

      facilitatorManager.getFacilitatorDetailWithCallbacks(
        aid,
        (data) => {
          if (mounted) {
            setFacilitator(data);

            // Format dates properly for HTML date inputs
            const formatDateForInput = (dateValue) => {
              if (!dateValue) return "";
              try {
                const date = new Date(dateValue);
                if (isNaN(date.getTime())) return "";
                // Check if date is the zero/minimum date (0001-01-01)
                if (date.getFullYear() < 1900) return "";
                return date.toISOString().split("T")[0];
              } catch (e) {
                return "";
              }
            };

            // Load specializations and certifications
            const certIds = data.certifications ? data.certifications.map((cert) => cert.id) : [];
            const specIds = data.specializations ? data.specializations.map((spec) => spec.id) : [];

            setSpecializationsAndCertifications({
              certificationIds: certIds,
              specializationIds: specIds,
              _items: [], // Will be reconstructed by the picker
            });

            // Map the API response to our form state
            setFacilitatorData({
              type: data.type ? data.type.toString() : "1",
              representitiveOrganizationName:
                data.representitiveOrganizationName || "",
              representitiveOrganizationType:
                data.representitiveOrganizationType || 0,
              firstName: data.firstName || "",
              lastName: data.lastName || "",
              email: data.email || "",
              phone: data.phone || "",
              phoneType: data.phoneType || 0,
              phoneExtension: data.phoneExtension || "",
              otherPhone: data.otherPhone || "",
              otherPhoneType: data.otherPhoneType || 0,
              otherPhoneExtension: data.otherPhoneExtension || "",
              isOkToText: data.isOkToText || false,
              isOkToEmail: data.isOkToEmail || false,
              country: data.country || "Canada",
              region: data.region || "",
              city: data.city || "",
              addressLine1: data.addressLine1 || "",
              addressLine2: data.addressLine2 || "",
              postalCode: data.postalCode || "",
              hasShippingAddress: data.hasShippingAddress || false,
              shippingName: data.shippingName || "",
              shippingPhone: data.shippingPhone || "",
              shippingCountry: data.shippingCountry || "Canada",
              shippingRegion: data.shippingRegion || "",
              shippingCity: data.shippingCity || "",
              shippingAddressLine1: data.shippingAddressLine1 || "",
              shippingAddressLine2: data.shippingAddressLine2 || "",
              shippingPostalCode: data.shippingPostalCode || "",
              skillSets: data.skillSets
                ? data.skillSets.map((ss) => ss.id)
                : [],
              insuranceRequirements: data.insuranceRequirements
                ? data.insuranceRequirements.map((ir) => ir.id)
                : [],
              vehicleTypes: data.vehicleTypes
                ? data.vehicleTypes.map((vt) => vt.id)
                : [],
              tags: data.tags ? data.tags.map((tag) => tag.id) : [],
              certifications: data.certifications
                ? data.certifications.map((cert) => cert.id)
                : [],
              serviceFeeId: data.serviceFeeId || "",
              hourlySalaryDesired: data.hourlySalaryDesired || 0,
              limitSpecial: data.limitSpecial || "",
              commercialInsuranceExpiryDate: formatDateForInput(
                data.commercialInsuranceExpiryDate,
              ),
              autoInsuranceExpiryDate: formatDateForInput(
                data.autoInsuranceExpiryDate,
              ),
              wsibNumber: data.wsibNumber || "",
              wsibInsuranceDate: formatDateForInput(data.wsibInsuranceDate),
              policeCheck: formatDateForInput(data.policeCheck),
              taxId: data.taxId || "",
              driversLicenseClass: data.driversLicenseClass || "",
              emergencyContactName: data.emergencyContactName || "",
              emergencyContactRelationship:
                data.emergencyContactRelationship || "",
              emergencyContactTelephone: data.emergencyContactTelephone || "",
              emergencyContactAlternativeTelephone:
                data.emergencyContactAlternativeTelephone || "",
              howDidYouHearAboutUsID: data.howDidYouHearAboutUsID || "",
              isHowDidYouHearAboutUsOther:
                data.isHowDidYouHearAboutUsOther || false,
              howDidYouHearAboutUsOther: data.howDidYouHearAboutUsOther || "",
              gender: data.gender || 0,
              genderOther: data.genderOther || "",
              birthDate: formatDateForInput(data.birthDate),
              joinDate: formatDateForInput(data.joinDate),
              additionalComment: data.additionalComment || "",
              identifyAs: data.identifyAs || [],
              isJobSeeker: data.isJobSeeker || 2,
              statusInCountry: data.statusInCountry || 0,
              statusInCountryOther: data.statusInCountryOther || "",
              countryOfOrigin: data.countryOfOrigin || "",
              dateOfEntryIntoCountry: formatDateForInput(
                data.dateOfEntryIntoCountry,
              ),
              maritalStatus: data.maritalStatus || 0,
              maritalStatusOther: data.maritalStatusOther || "",
              accomplishedEducation: data.accomplishedEducation || 0,
              accomplishedEducationOther: data.accomplishedEducationOther || "",
              description: data.description || "",
              preferredLanguage: data.preferredLanguage || "English",
              // Handle level - ensure it's a number or empty string
              level: data.level ? parseInt(data.level) : "",
              availability: data.availability || {
                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 },
              },
            });

            setIsLoading(false);
          }
        },
        (error) => {
          if (mounted) {
            setAlert({
              type: "error",
              message: "Failed to load facilitator details. Please try again.",
            });
            setIsLoading(false);
          }
        },
        () => {},
        onUnauthorized,
      );
    };

    fetchFacilitatorDetail();

    return () => {
      mounted = false;
    };
  }, [aid, facilitatorManager, navigate]);

  const handleInputChange = useCallback((field, value) => {
    setFacilitatorData((prev) => ({
      ...prev,
      [field]: value,
    }));

    setErrors((prev) => {
      if (prev[field]) {
        const { [field]: removed, ...rest } = prev;
        return rest;
      }
      return prev;
    });
  }, []);

  const handleCheckboxChange = useCallback((field) => {
    setFacilitatorData((prev) => ({
      ...prev,
      [field]: !prev[field],
    }));
  }, []);

  // Handler for availability checkbox changes
  const handleAvailabilityChange = useCallback((day, period) => {
    setFacilitatorData((prev) => ({
      ...prev,
      availability: {
        ...prev.availability,
        [day]: {
          ...prev.availability[day],
          [period]: !prev.availability[day][period],
        },
      },
    }));

    // Clear availability error if it exists
    setErrors((prev) => {
      if (prev.availability) {
        const { availability: removed, ...rest } = prev;
        return rest;
      }
      return prev;
    });
  }, []);

  // Check if at least one availability slot is selected
  const hasAvailabilitySelected = useCallback(() => {
    return Object.values(facilitatorData.availability).some(
      (day) => day.am || day.pm,
    );
  }, [facilitatorData.availability]);

  const validateForm = useCallback(() => {
    const newErrors = {};

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

    // Representative facilitator validation
    if (facilitatorData.type === "2") {
      if (!facilitatorData.representitiveOrganizationName.trim()) {
        newErrors.representitiveOrganizationName =
          "Organization name is required for representative facilitators";
      }
      if (!facilitatorData.representitiveOrganizationType) {
        newErrors.representitiveOrganizationType =
          "Organization type is required for representative facilitators";
      }
    }

    // Address validation
    if (!facilitatorData.country) {
      newErrors.country = "Country is required";
    }
    if (!facilitatorData.region.trim()) {
      newErrors.region = "Province/Territory is required";
    }
    if (!facilitatorData.city.trim()) {
      newErrors.city = "City is required";
    }
    if (!facilitatorData.addressLine1.trim()) {
      newErrors.addressLine1 = "Address line 1 is required";
    }
    if (!facilitatorData.postalCode.trim()) {
      newErrors.postalCode = "Postal code is required";
    }

    // Shipping address validation if enabled
    if (facilitatorData.hasShippingAddress) {
      if (!facilitatorData.shippingName.trim()) {
        newErrors.shippingName = "Shipping name is required";
      }
      if (!facilitatorData.shippingPhone.trim()) {
        newErrors.shippingPhone = "Shipping phone is required";
      }
      if (!facilitatorData.shippingCountry) {
        newErrors.shippingCountry = "Shipping country is required";
      }
      if (!facilitatorData.shippingRegion.trim()) {
        newErrors.shippingRegion = "Shipping province/territory is required";
      }
      if (!facilitatorData.shippingCity.trim()) {
        newErrors.shippingCity = "Shipping city is required";
      }
      if (!facilitatorData.shippingAddressLine1.trim()) {
        newErrors.shippingAddressLine1 = "Shipping address line 1 is required";
      }
      if (!facilitatorData.shippingPostalCode.trim()) {
        newErrors.shippingPostalCode = "Shipping postal code is required";
      }
    }

    // Professional fields validation
    // Skill sets are now optional
    if (
      !facilitatorData.insuranceRequirements ||
      facilitatorData.insuranceRequirements.length === 0
    ) {
      newErrors.insuranceRequirements =
        "At least one insurance requirement is required";
    }
    // At least one specialization and certification is required
    if (!specializationsAndCertifications.specializationIds ||
        specializationsAndCertifications.specializationIds.length === 0) {
      newErrors.certifications = "At least one specialization is required";
    } else if (!specializationsAndCertifications.certificationIds ||
               specializationsAndCertifications.certificationIds.length === 0) {
      newErrors.certifications = "At least one certification is required";
    }
    if (!facilitatorData.serviceFeeId) {
      newErrors.serviceFeeId = "Service fee is required";
    }
    if (!facilitatorData.policeCheck) {
      newErrors.policeCheck = "Police check date is required";
    }
    // Commercial insurance expiry date is now optional
    if (!facilitatorData.hourlySalaryDesired || facilitatorData.hourlySalaryDesired <= 0) {
      newErrors.hourlySalaryDesired = "Hourly salary desired is required and must be greater than 0";
    }

    // Metrics validation
    // How did you hear about us is now optional
    if (
      facilitatorData.howDidYouHearAboutUsID &&
      facilitatorData.isHowDidYouHearAboutUsOther &&
      !facilitatorData.howDidYouHearAboutUsOther.trim()
    ) {
      newErrors.howDidYouHearAboutUsOther = "Please specify other option";
    }
    // Gender is now optional
    if (facilitatorData.gender === 1 && !facilitatorData.genderOther.trim()) {
      newErrors.genderOther = "Please specify other gender";
    }
    // Birth date is now optional
    if (!facilitatorData.preferredLanguage) {
      newErrors.preferredLanguage = "Preferred language is required";
    }

    // Level validation
    if (!facilitatorData.level) {
      newErrors.level = "Facilitator level is required";
    }

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

    return newErrors;
  }, [facilitatorData, hasAvailabilitySelected, specializationsAndCertifications]);

  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();

    setAlert(null);

    // Validate form
    const formErrors = validateForm();
    if (Object.keys(formErrors).length > 0) {
      setErrors(formErrors);

      const errorList = formatErrorsForAlert(formErrors);
      if (errorList) {
        setAlert({
          type: "error",
          message: "Please correct the following errors:",
          details: errorList,
        });
      } else {
        setAlert({
          type: "error",
          message: "Please correct the errors in the form before submitting.",
        });
      }

      window.scrollTo(0, 0);
      return;
    }

    setIsSaving(true);
    setErrors({});

    // Format dates for API submission
    const formatDateForAPI = (dateValue) => {
      if (!dateValue) return "";
      try {
        const date = new Date(dateValue);
        if (isNaN(date.getTime())) return "";
        return date.toISOString();
      } catch (e) {
        return "";
      }
    };

    // Prepare data for submission
    const submitData = {
      id: aid,
      ...facilitatorData,
      type: parseInt(facilitatorData.type),
      representitive_organization_name:
        facilitatorData.representitiveOrganizationName || "",
      representitive_organization_type:
        facilitatorData.representitiveOrganizationType
          ? parseInt(facilitatorData.representitiveOrganizationType)
          : 0,
      phoneType: facilitatorData.phoneType
        ? parseInt(facilitatorData.phoneType)
        : 0,
      otherPhoneType: facilitatorData.otherPhoneType
        ? parseInt(facilitatorData.otherPhoneType)
        : 0,
      hourlySalaryDesired: facilitatorData.hourlySalaryDesired
        ? parseInt(facilitatorData.hourlySalaryDesired)
        : 0,
      isJobSeeker: facilitatorData.isJobSeeker
        ? parseInt(facilitatorData.isJobSeeker)
        : 2,
      gender: facilitatorData.gender ? parseInt(facilitatorData.gender) : 0,
      birthDate: formatDateForAPI(facilitatorData.birthDate),
      joinDate: formatDateForAPI(facilitatorData.joinDate),
      commercialInsuranceExpiryDate: formatDateForAPI(
        facilitatorData.commercialInsuranceExpiryDate,
      ),
      autoInsuranceExpiryDate: formatDateForAPI(
        facilitatorData.autoInsuranceExpiryDate,
      ),
      wsibInsuranceDate: formatDateForAPI(facilitatorData.wsibInsuranceDate),
      policeCheck: formatDateForAPI(facilitatorData.policeCheck),
      dateOfEntryIntoCountry: formatDateForAPI(
        facilitatorData.dateOfEntryIntoCountry,
      ),
      skillSets: facilitatorData.skillSets || [],
      insuranceRequirements: facilitatorData.insuranceRequirements || [],
      vehicleTypes: facilitatorData.vehicleTypes || [],
      tags: facilitatorData.tags || [],
      identifyAs: facilitatorData.identifyAs || [],
      certification_ids: specializationsAndCertifications.certificationIds || [],
      specialization_ids: specializationsAndCertifications.specializationIds || [],
      // Convert level to integer for backend
      level: facilitatorData.level ? parseInt(facilitatorData.level) : null,
      availability: facilitatorData.availability, // Availability is already properly formatted
    };

    // Handle optional numeric fields
    if (facilitatorData.statusInCountry) {
      submitData.statusInCountry = parseInt(facilitatorData.statusInCountry);
    }
    if (facilitatorData.maritalStatus) {
      submitData.maritalStatus = parseInt(facilitatorData.maritalStatus);
    }
    if (facilitatorData.accomplishedEducation) {
      submitData.accomplishedEducation = parseInt(
        facilitatorData.accomplishedEducation,
      );
    }

    facilitatorManager.updateFacilitatorWithCallbacks(
      aid,
      submitData,
      (data) => {
        setAlert({
          type: "success",
          message: "Facilitator updated successfully!",
        });

        setTimeout(() => {
          navigate(`/admin/facilitator/${aid}`);
        }, 2000);
      },
      (error) => {
        if (error && typeof error === "object") {
          const hasFieldErrors = Object.keys(error).some(
            (key) => key !== "message" && key !== "general" && key !== "detail",
          );

          if (hasFieldErrors) {
            setErrors(error);
            const errorList = formatErrorsForAlert(error);

            if (errorList) {
              setAlert({
                type: "error",
                message:
                  error.general ||
                  "Failed to update facilitator. Please correct the following errors:",
                details: errorList,
              });
            } else {
              setAlert({
                type: "error",
                message:
                  error.general ||
                  error.message ||
                  "Failed to update facilitator. Please check the form and try again.",
              });
            }
          } else {
            setAlert({
              type: "error",
              message:
                error.message ||
                error.detail ||
                "Failed to update facilitator. Please try again.",
            });
          }
        } else {
          setAlert({
            type: "error",
            message: "An unexpected error occurred. Please try again.",
          });
        }

        window.scrollTo(0, 0);
      },
      () => {
        setIsSaving(false);
      },
      onUnauthorized,
    );
  }, [aid, facilitatorData, facilitatorManager, navigate, onUnauthorized, validateForm]);

  const handleServiceFeeChange = useCallback((value) => {
    handleInputChange("serviceFeeId", value);
  }, [handleInputChange]);

  // Memoize tabs array to prevent unnecessary re-renders
  const tabs = useMemo(() => [
    {
      id: "summary",
      label: "Summary",
      to: `/admin/facilitator/${aid}`,
    },
    {
      id: "detail",
      label: "Full Details",
      to: `/admin/facilitator/${aid}/detail`,
    },
    {
      id: "event-contracts",
      label: "Event Contracts",
      to: `/admin/facilitator/${aid}/event-contracts`,
    },
    {
      id: "comments",
      label: "Comments",
      to: `/admin/facilitator/${aid}/comments`,
    },
    {
      id: "attachments",
      label: "Attachments",
      to: `/admin/facilitator/${aid}/attachments`,
    },
    {
      id: "more",
      label: "More",
      to: `/admin/facilitator/${aid}/more`,
      icon: EllipsisHorizontalIcon,
    },
  ], [aid]);

  if (isLoading) {
    return (
      <UIXThemeProvider>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <Spinner size="lg" />
              <p className={`mt-4 text-sm sm:text-base ${getThemeClasses('text-secondary')}`}>
                Loading facilitator details...
              </p>
            </div>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
        {/* Breadcrumb */}
        <Breadcrumb
          items={[
            { label: "Dashboard", href: "/admin/dashboard", icon: ChartBarIcon },
            { label: "Facilitators", href: "/admin/facilitators", icon: UserGroupIcon },
            { label: "Detail", href: `/admin/facilitator/${aid}`, icon: InformationCircleIcon },
            { label: "Update", icon: PencilSquareIcon },
          ]}
          className="mb-4 sm:mb-6"
        />

        {/* Status Alerts */}
        {facilitator && facilitator.status === 2 && (
          <Alert
            type="info"
            message="This facilitator is archived"
            icon={ArchiveBoxIcon}
            className="mb-4"
          />
        )}
        {facilitator && facilitator.isBanned && (
          <Alert
            type="error"
            message="This facilitator is banned"
            icon={NoSymbolIcon}
            className="mb-4"
          />
        )}

      {/* Alert Messages */}
      {alert && (
        <Alert
          type={alert.type}
          message={alert.message}
          details={alert.details}
          onClose={() => setAlert(null)}
          className="mb-4"
        />
      )}

      {/* Main Content */}
      <div className={`${getThemeClasses('bg-primary')} shadow-sm rounded-lg`}>
        {/* Header with Actions - Responsive */}
        <div className={`px-4 sm:px-6 py-4 sm:py-5 border-b ${getThemeClasses('card-border')}`}>
          <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 sm:gap-4">
            <h2 className={`text-xl sm:text-2xl font-semibold ${getThemeClasses('text-primary')} flex items-center`}>
              <PencilSquareIcon className={`w-5 sm:w-7 h-5 sm:h-7 mr-2 ${getThemeClasses('text-accent')} flex-shrink-0`} />
              Update Facilitator
            </h2>
            <Button
              variant="outline"
              onClick={() => navigate(`/admin/facilitator/${aid}`)}
              icon={ChevronLeftIcon}
              className="flex-shrink-0"
            >
              Back to Detail
            </Button>
          </div>
        </div>

        {/* Tab Navigation */}
        <Tabs mode="routing" tabs={tabs} />

        <form onSubmit={handleSubmit} className="p-4 sm:p-6">
          {/* Contact Information Section */}
          <FormCard
            title="Contact Information"
            icon={UserIcon}
            description="Contact details and communication preferences"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              {/* Organization fields for representative facilitators */}
              {facilitatorData.type === "2" && (
                <FormRow columns={2}>
                  <Input
                    label="Organization Name"
                    value={facilitatorData.representitiveOrganizationName}
                    onChange={(value) =>
                      handleInputChange(
                        "representitiveOrganizationName",
                        value,
                      )
                    }
                    error={errors.representitiveOrganizationName}
                    required
                  />

                  <Select
                    label="Organization Type"
                    value={facilitatorData.representitiveOrganizationType}
                    onChange={(value) =>
                      handleInputChange(
                        "representitiveOrganizationType",
                        parseInt(value),
                      )
                    }
                    options={ORGANIZATION_TYPE_OPTIONS}
                    error={errors.representitiveOrganizationType}
                  />
                </FormRow>
              )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
              <Input
                label="First Name"
                value={facilitatorData.firstName}
                onChange={(value) => handleInputChange("firstName", value)}
                error={errors.firstName}
                required
              />

              <Input
                label="Last Name"
                value={facilitatorData.lastName}
                onChange={(value) => handleInputChange("lastName", value)}
                error={errors.lastName}
                required
              />
            </div>

            <div className="mb-4 sm:mb-6">
              <Input
                label="Email"
                type="email"
                value={facilitatorData.email}
                onChange={(value) => handleInputChange("email", value)}
                error={errors.email}
                required
              />
            </div>

            <div className="mb-4 sm:mb-6">
              <Checkbox
                label="I agree to receive electronic email"
                checked={facilitatorData.isOkToEmail}
                onChange={() => handleCheckboxChange("isOkToEmail")}
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
              <Input
                label="Phone"
                type="tel"
                value={facilitatorData.phone}
                onChange={(value) => handleInputChange("phone", value)}
                error={errors.phone}
                required
              />

              <Select
                label="Phone Type"
                value={facilitatorData.phoneType}
                onChange={(value) =>
                  handleInputChange("phoneType", parseInt(value))
                }
                options={PHONE_TYPE_OPTIONS}
                error={errors.phoneType}
              />
            </div>

            {facilitatorData.phoneType === 2 && (
              <div className="mb-4 sm:mb-6">
                <Input
                  label="Phone Extension"
                  value={facilitatorData.phoneExtension}
                  onChange={(value) =>
                    handleInputChange("phoneExtension", value)
                  }
                  error={errors.phoneExtension}
                />
              </div>
            )}

            <div className="mb-4 sm:mb-6">
              <Checkbox
                label="I agree to receive texts to my phone"
                checked={facilitatorData.isOkToText}
                onChange={() => handleCheckboxChange("isOkToText")}
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-6 mb-4 sm:mb-6">
              <Input
                label="Other Phone (Optional)"
                type="tel"
                value={facilitatorData.otherPhone}
                onChange={(value) =>
                  handleInputChange("otherPhone", value)
                }
                error={errors.otherPhone}
              />

              <Select
                label="Other Phone Type"
                value={facilitatorData.otherPhoneType}
                onChange={(value) =>
                  handleInputChange("otherPhoneType", parseInt(value))
                }
                options={PHONE_TYPE_OPTIONS}
                error={errors.otherPhoneType}
              />
            </div>

            {facilitatorData.otherPhoneType === 2 && (
              <div className="mb-4 sm:mb-6">
                <Input
                  label="Other Phone Extension"
                  value={facilitatorData.otherPhoneExtension}
                  onChange={(value) =>
                    handleInputChange("otherPhoneExtension", value)
                  }
                  error={errors.otherPhoneExtension}
                />
              </div>
            )}
            </FormSection>
          </FormCard>

          {/* Address Section */}
          <FormCard
            title="Address"
            icon={MapPinIcon}
            description="Billing and shipping address information"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="mb-4 sm:mb-6">
              <Checkbox
                label="Has shipping address different than billing address"
                checked={facilitatorData.hasShippingAddress}
                onChange={() => handleCheckboxChange("hasShippingAddress")}
              />
            </div>

            <div
              className={`grid ${facilitatorData.hasShippingAddress ? "grid-cols-1 lg:grid-cols-2" : "grid-cols-1"} gap-6 sm:gap-8`}
            >
              {/* Billing Address */}
              <div>
                {facilitatorData.hasShippingAddress && (
                  <h4 className={`text-sm sm:text-base font-medium ${getThemeClasses('text-primary')} mb-3 sm:mb-4`}>
                    Billing Address
                  </h4>
                )}

                <div className="space-y-3 sm:space-y-4">
                  <Input
                    label="Country"
                    value={facilitatorData.country}
                    onChange={(value) =>
                      handleInputChange("country", value)
                    }
                    error={errors.country}
                    required
                  />

                  <Select
                    label="Province/Territory"
                    value={facilitatorData.region}
                    onChange={(value) =>
                      handleInputChange("region", value)
                    }
                    options={REGION_OPTIONS}
                    error={errors.region}
                    required
                  />

                  <Input
                    label="City"
                    value={facilitatorData.city}
                    onChange={(value) => handleInputChange("city", value)}
                    error={errors.city}
                    required
                  />

                  <Input
                    label="Address Line 1"
                    value={facilitatorData.addressLine1}
                    onChange={(value) =>
                      handleInputChange("addressLine1", value)
                    }
                    error={errors.addressLine1}
                    required
                  />

                  <Input
                    label="Address Line 2 (Optional)"
                    value={facilitatorData.addressLine2}
                    onChange={(value) =>
                      handleInputChange("addressLine2", value)
                    }
                    error={errors.addressLine2}
                  />

                  <Input
                    label="Postal Code"
                    value={facilitatorData.postalCode}
                    onChange={(value) =>
                      handleInputChange("postalCode", value)
                    }
                    error={errors.postalCode}
                    required
                  />
                </div>
              </div>

              {/* Shipping Address */}
              {facilitatorData.hasShippingAddress && (
                <div>
                  <h4 className={`text-sm sm:text-base font-medium ${getThemeClasses('text-primary')} mb-3 sm:mb-4`}>
                    Shipping Address
                  </h4>

                  <div className="space-y-3 sm:space-y-4">
                    <Input
                      label="Name"
                      value={facilitatorData.shippingName}
                      onChange={(value) =>
                        handleInputChange("shippingName", value)
                      }
                      placeholder="The name to contact for this shipping address"
                      error={errors.shippingName}
                      required
                    />

                    <Input
                      label="Phone"
                      type="tel"
                      value={facilitatorData.shippingPhone}
                      onChange={(value) =>
                        handleInputChange("shippingPhone", value)
                      }
                      placeholder="The contact phone number for this shipping address"
                      error={errors.shippingPhone}
                      required
                    />

                    <Input
                      label="Country"
                      value={facilitatorData.shippingCountry}
                      onChange={(value) =>
                        handleInputChange("shippingCountry", value)
                      }
                      error={errors.shippingCountry}
                      required
                    />

                    <Select
                      label="Province/Territory"
                      value={facilitatorData.shippingRegion}
                      onChange={(value) =>
                        handleInputChange("shippingRegion", value)
                      }
                      options={REGION_OPTIONS}
                      error={errors.shippingRegion}
                      required
                    />

                    <Input
                      label="City"
                      value={facilitatorData.shippingCity}
                      onChange={(value) =>
                        handleInputChange("shippingCity", value)
                      }
                      error={errors.shippingCity}
                      required
                    />

                    <Input
                      label="Address Line 1"
                      value={facilitatorData.shippingAddressLine1}
                      onChange={(value) =>
                        handleInputChange(
                          "shippingAddressLine1",
                          value,
                        )
                      }
                      error={errors.shippingAddressLine1}
                      required
                    />

                    <Input
                      label="Address Line 2 (Optional)"
                      value={facilitatorData.shippingAddressLine2}
                      onChange={(value) =>
                        handleInputChange(
                          "shippingAddressLine2",
                          value,
                        )
                      }
                      error={errors.shippingAddressLine2}
                    />

                    <Input
                      label="Postal Code"
                      value={facilitatorData.shippingPostalCode}
                      onChange={(value) =>
                        handleInputChange("shippingPostalCode", value)
                      }
                      error={errors.shippingPostalCode}
                      required
                    />
                  </div>
                </div>
              )}
            </div>
            </FormSection>
          </FormCard>

          {/* Level Section */}
          <FormCard
            title="Level"
            icon={ChartBarIcon}
            description="Facilitator level and experience"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="max-w-xl">
              <Select
                label="Facilitator Level"
                value={facilitatorData.level}
                onChange={(value) =>
                  handleInputChange(
                    "level",
                    value ? parseInt(value) : "",
                  )
                }
                options={FACILITATOR_LEVEL_OPTIONS}
                error={errors.level}
                required
                helperText="Level 1 facilitators are unpaid volunteers, while Level 2 facilitators receive compensation for their services."
              />
            </div>
            </FormSection>
          </FormCard>

          {/* Professional Information Section */}
          <FormCard
            title="Professional Information"
            icon={BriefcaseIcon}
            description="Skills, certifications, and professional details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="space-y-4 sm:space-y-6">
              {/* Specializations & Certifications */}
              <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}
              />

              <SkillSetsMultiSelect
                value={facilitatorData.skillSets}
                onChange={(value) => handleInputChange("skillSets", value)}
                error={errors.skillSets}
                required={false}
                label="Skill Sets (Optional)"
                helperText="Select all skill sets that apply to this facilitator"
                onUnauthorized={onUnauthorized}
              />

              <InsuranceRequirementsMultiSelect
                value={facilitatorData.insuranceRequirements}
                onChange={(value) =>
                  handleInputChange("insuranceRequirements", value)
                }
                error={errors.insuranceRequirements}
                required={false}
                label="Insurance Requirements (Optional)"
                helperText="Select all insurance requirements for this facilitator"
                onUnauthorized={onUnauthorized}
              />

              <ServiceFeeSelect
                value={facilitatorData.serviceFeeId}
                onChange={handleServiceFeeChange}
                error={errors.serviceFeeId}
                required={true}
                label="Service Fee"
                helperText="Select the applicable service fee for this facilitator"
                onUnauthorized={onUnauthorized}
              />

              <Input
                label="Police Check Expiry"
                type="date"
                value={facilitatorData.policeCheck}
                onChange={(value) => handleInputChange("policeCheck", value)}
                error={errors.policeCheck}
                required
              />

              <Input
                label="Tax ID (Optional)"
                value={facilitatorData.taxId}
                onChange={(value) => handleInputChange("taxId", value)}
                error={errors.taxId}
              />

              <Input
                label="Hourly Salary Desired"
                type="number"
                value={facilitatorData.hourlySalaryDesired}
                onChange={(value) =>
                  handleInputChange("hourlySalaryDesired", value)
                }
                error={errors.hourlySalaryDesired}
                required
              />
            </div>
            </FormSection>
          </FormCard>

          {/* Availability Section */}
          <FormCard
            title="Availability"
            icon={ClockIcon}
            description="Weekly availability schedule"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div>
              <p className={`text-sm sm:text-base ${getThemeClasses('text-muted')} mb-4`}>
                Select the time slots when the facilitator is available
              </p>
              <div className="overflow-x-auto">
                <table className={`min-w-full divide-y ${getThemeClasses('card-border')}`}>
                  <thead className={getThemeClasses('table-header-bg')}>
                    <tr>
                      <th className={`px-3 sm:px-6 py-2 sm:py-3 text-left text-sm sm:text-base font-medium ${getThemeClasses('table-header-text')} uppercase tracking-wider`}>
                        Day
                      </th>
                      <th className={`px-3 sm:px-6 py-2 sm:py-3 text-center text-sm sm:text-base font-medium ${getThemeClasses('table-header-text')} uppercase tracking-wider`}>
                        AM
                      </th>
                      <th className={`px-3 sm:px-6 py-2 sm:py-3 text-center text-sm sm:text-base font-medium ${getThemeClasses('table-header-text')} uppercase tracking-wider`}>
                        PM
                      </th>
                    </tr>
                  </thead>
                  <tbody className={`${getThemeClasses('bg-primary')} divide-y ${getThemeClasses('card-border')}`}>
                    {[
                      { 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" },
                    ].map((day) => (
                      <tr key={day.key} className={getThemeClasses('table-row-hover')}>
                        <td className={`px-3 sm:px-6 py-3 sm:py-4 whitespace-nowrap text-base sm:text-lg font-medium ${getThemeClasses('text-primary')}`}>
                          {day.label}
                        </td>
                        <td className="px-3 sm:px-6 py-3 sm:py-4 whitespace-nowrap text-center">
                          <Checkbox
                            checked={facilitatorData.availability[day.key].am}
                            onChange={() =>
                              handleAvailabilityChange(day.key, "am")
                            }
                            aria-label={`${day.label} AM availability`}
                          />
                        </td>
                        <td className="px-3 sm:px-6 py-3 sm:py-4 whitespace-nowrap text-center">
                          <Checkbox
                            checked={facilitatorData.availability[day.key].pm}
                            onChange={() =>
                              handleAvailabilityChange(day.key, "pm")
                            }
                            aria-label={`${day.label} PM availability`}
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              {errors.availability && (
                <p className={`mt-2 text-sm sm:text-base ${getThemeClasses('text-error')}`}>
                  {errors.availability}
                </p>
              )}
              <p className={`mt-3 text-sm sm:text-base ${getThemeClasses('text-muted')}`}>
                <span className="font-medium">Note:</span> At least one time
                slot must be selected to indicate when the facilitator is
                available.
              </p>
            </div>
            </FormSection>
          </FormCard>

          {/* Metrics Section */}
          <FormCard
            title="Metrics"
            icon={ChartPieIcon}
            description="Demographics and additional information"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="space-y-4 sm:space-y-6">
              <TagsMultiSelect
                value={facilitatorData.tags}
                onChange={(value) => handleInputChange("tags", value)}
                error={errors.tags}
                required={false}
                label="Tags (Optional)"
                helperText="Select tags to categorize this facilitator"
                onUnauthorized={onUnauthorized}
              />

              <Select
                label="Gender (Optional)"
                value={facilitatorData.gender}
                onChange={(value) =>
                  handleInputChange("gender", parseInt(value))
                }
                options={GENDER_OPTIONS}
                error={errors.gender}
              />

              {facilitatorData.gender === 1 && (
                <Input
                  label="Gender (Other)"
                  value={facilitatorData.genderOther}
                  onChange={(value) =>
                    handleInputChange("genderOther", value)
                  }
                  error={errors.genderOther}
                  required
                />
              )}

              <Input
                label="Join Date (Optional)"
                type="date"
                value={facilitatorData.joinDate}
                onChange={(value) => handleInputChange("joinDate", value)}
                error={errors.joinDate}
                helperText="This indicates when the facilitator joined the workery"
              />

              <Textarea
                label="Additional Comment (Optional)"
                value={facilitatorData.additionalComment}
                onChange={(value) =>
                  handleInputChange("additionalComment", value)
                }
                rows={4}
                maxLength={638}
                helperText={`${facilitatorData.additionalComment.length}/638 characters`}
              />
            </div>
            </FormSection>
          </FormCard>

          {/* System Information Section */}
          <FormCard
            title="System Information"
            icon={ComputerDesktopIcon}
            description="System settings and preferences"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="max-w-xl">
              <Select
                label="Preferred Language"
                value={facilitatorData.preferredLanguage}
                onChange={(value) =>
                  handleInputChange("preferredLanguage", value)
                }
                options={LANGUAGE_OPTIONS}
                error={errors.preferredLanguage}
                required
              />
            </div>
            </FormSection>
          </FormCard>

          {/* Form Actions */}
          <div className={`flex flex-col sm:flex-row sm:justify-between items-stretch sm:items-center mt-6 sm:mt-8 pt-4 sm:pt-6 border-t ${getThemeClasses('border-secondary')} gap-3`}>
            <Button
              type="button"
              variant="outline"
              onClick={() => navigate(`/admin/facilitator/${aid}`)}
              icon={ChevronLeftIcon}
              className="order-2 sm:order-1"
            >
              Back to Detail
            </Button>

            <Button
              type="submit"
              variant="primary"
              disabled={isSaving}
              loading={isSaving}
              icon={CheckCircleIcon}
              className="order-1 sm:order-2"
            >
              {isSaving ? "Saving..." : "Save Changes"}
            </Button>
          </div>
        </form>
      </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorUpdatePage;
