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

import React, { useState, useEffect, useCallback, useMemo } 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 {
  useSpeakerManager,
  useAuthManager,
  useSkillSetManager,
} from "../../../../services/Services";
import {
  InsuranceRequirementsMultiSelect,
  ServiceFeeSelect,
  TagsMultiSelect,
} from "../../../../components/business/selects";
import {
  UIXThemeProvider,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  Textarea,
  Button,
  Alert,
  Breadcrumb,
  Tabs,
  Spinner,
  useUIXTheme,
} from "../../../../components/UIX";

// Constants

// Speaker level constants - matching backend integer values
const SPEAKER_LEVEL_IN_TRAINING = 1;
const SPEAKER_LEVEL_SECONDARY_FACILITATOR = 2;
const SPEAKER_LEVEL_LEAD_FACILITATOR = 3;
const SPEAKER_LEVEL_TRAINER = 4;

// Level options to use integer values
const SPEAKER_LEVEL_OPTIONS = [
  { value: "", label: "Select a level" },
  { value: SPEAKER_LEVEL_IN_TRAINING, label: "Level 1 (in training)" },
  {
    value: SPEAKER_LEVEL_SECONDARY_FACILITATOR,
    label: "Level 2 (secondary speaker)",
  },
  {
    value: SPEAKER_LEVEL_LEAD_FACILITATOR,
    label: "Level 3 (lead speaker)",
  },
  {
    value: SPEAKER_LEVEL_TRAINER,
    label: "Level 4 (trainer)",
  },
];

const SPEAKER_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" && field !== "detail" && field !== "message") {
      // Convert camelCase or snake_case to readable format
      const fieldName = field
        .replace(/_/g, " ") // Convert underscores to spaces
        .replace(/([A-Z])/g, " $1") // Add space before capital letters
        .replace(/^./, (str) => str.toUpperCase()) // Capitalize first letter
        .trim()
        .replace(/\s+/g, " "); // Remove multiple spaces

      // Ensure message is a string
      const errorMessage = typeof message === "string" ? message : JSON.stringify(message);
      errorList.push(`• ${fieldName}: ${errorMessage}`);
    }
  }

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

function AdminSpeakerUpdatePage() {
  const { aid } = useParams();
  const navigate = useNavigate();
  const speakerManager = useSpeakerManager();
  const authManager = useAuthManager();
  const skillSetManager = useSkillSetManager();
  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 [speaker, setSpeaker] = useState(null);

  // Skill sets tag/pill UI states
  const [currentSkillSetId, setCurrentSkillSetId] = useState("");
  const [selectedSkillSets, setSelectedSkillSets] = useState([]);
  const [skillSetOptions, setSkillSetOptions] = useState([]);

  // Speaker data state - Complete fields based on backend requirements
  const [speakerData, setSpeakerData] = 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: [],
    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]);

  // Fetch skill set options for the tag/pill UI
  useEffect(() => {
    const fetchSkillSetOptions = async () => {
      try {
        const options = await skillSetManager.getSkillSetSelectOptions(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.text || opt.name || `Skill Set ${opt.id}`,
          }));
          setSkillSetOptions(formattedOptions);
        }
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Failed to fetch skill set options:", error);
        }
      }
    };
    fetchSkillSetOptions();
  }, [skillSetManager, onUnauthorized]);

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

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

      speakerManager.getSpeakerDetailWithCallbacks(
        aid,
        (data) => {
          if (mounted) {
            setSpeaker(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 skill sets into the selected state for tag/pill UI
            if (data.skillSets && data.skillSets.length > 0) {
              const formattedSkillSets = data.skillSets.map(ss => ({
                id: ss.id,
                name: ss.subCategory || ss.name || `Skill Set ${ss.id}`,
              }));
              setSelectedSkillSets(formattedSkillSets);
            }

            // Map the API response to our form state
            setSpeakerData({
              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 || "",
              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) : [],
              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 speaker details. Please try again.",
            });
            setIsLoading(false);
          }
        },
        () => {},
        onUnauthorized,
      );
    };

    fetchSpeakerDetail();

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

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

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

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

  // Handler for availability checkbox changes
  const handleAvailabilityChange = useCallback((day, period) => {
    setSpeakerData((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(speakerData.availability).some(
      (day) => day.am || day.pm,
    );
  }, [speakerData.availability]);

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

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

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

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

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

    // Professional fields validation
    if (!selectedSkillSets || selectedSkillSets.length === 0) {
      newErrors.skillSets = "At least one skill set is required";
    }
    if (
      !speakerData.insuranceRequirements ||
      speakerData.insuranceRequirements.length === 0
    ) {
      newErrors.insuranceRequirements =
        "At least one insurance requirement is required";
    }
    if (!speakerData.serviceFeeId) {
      newErrors.serviceFeeId = "Service fee is required";
    }
    if (!speakerData.policeCheck) {
      newErrors.policeCheck = "Police check date is required";
    }
    // Commercial insurance expiry date is now optional
    if (speakerData.hourlySalaryDesired == null || speakerData.hourlySalaryDesired === '' || speakerData.hourlySalaryDesired < 0) {
      newErrors.hourlySalaryDesired = "Hourly salary desired is required and cannot be negative";
    }

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

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

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

    return newErrors;
  }, [speakerData, hasAvailabilitySelected, selectedSkillSets]);

  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 (import.meta.env.DEV) {
        console.log("Validation errors:", formErrors); // Debug log
      }
      if (import.meta.env.DEV) {
        console.log("Formatted error list:", errorList); // Debug log
      }

      if (errorList && errorList.length > 0) {
        setAlert({
          type: "error",
          message: `Please correct the following ${errorList.length} error${errorList.length > 1 ? 's' : ''}:`,
          details: errorList,
        });
      } else {
        // Fallback: Show error count if formatting failed
        const errorCount = Object.keys(formErrors).length;
        const errorFields = Object.keys(formErrors).join(", ");
        setAlert({
          type: "error",
          message: `Please correct ${errorCount} error${errorCount > 1 ? 's' : ''} in the form before submitting.`,
          details: [`The following fields have errors: ${errorFields}`],
        });
      }

      // Scroll to first error field
      const firstErrorField = Object.keys(formErrors)[0];
      const element = document.querySelector(`[name="${firstErrorField}"], #${firstErrorField}, [data-field="${firstErrorField}"]`);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        // Try to focus if it's an input element
        if (element.focus) {
          setTimeout(() => element.focus(), 300);
        }
      } else {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
      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,
      ...speakerData,
      type: parseInt(speakerData.type),
      representitive_organization_name:
        speakerData.representitiveOrganizationName || "",
      representitive_organization_type:
        speakerData.representitiveOrganizationType
          ? parseInt(speakerData.representitiveOrganizationType)
          : 0,
      phoneType: speakerData.phoneType
        ? parseInt(speakerData.phoneType)
        : 0,
      otherPhoneType: speakerData.otherPhoneType
        ? parseInt(speakerData.otherPhoneType)
        : 0,
      hourlySalaryDesired: speakerData.hourlySalaryDesired
        ? parseInt(speakerData.hourlySalaryDesired)
        : 0,
      isJobSeeker: speakerData.isJobSeeker
        ? parseInt(speakerData.isJobSeeker)
        : 2,
      gender: speakerData.gender ? parseInt(speakerData.gender) : 0,
      birthDate: formatDateForAPI(speakerData.birthDate),
      joinDate: formatDateForAPI(speakerData.joinDate),
      commercialInsuranceExpiryDate: formatDateForAPI(
        speakerData.commercialInsuranceExpiryDate,
      ),
      autoInsuranceExpiryDate: formatDateForAPI(
        speakerData.autoInsuranceExpiryDate,
      ),
      wsibInsuranceDate: formatDateForAPI(speakerData.wsibInsuranceDate),
      policeCheck: formatDateForAPI(speakerData.policeCheck),
      dateOfEntryIntoCountry: formatDateForAPI(
        speakerData.dateOfEntryIntoCountry,
      ),
      skillSets: selectedSkillSets.map(ss => ss.id) || [],
      insuranceRequirements: speakerData.insuranceRequirements || [],
      vehicleTypes: speakerData.vehicleTypes || [],
      tags: speakerData.tags || [],
      identifyAs: speakerData.identifyAs || [],
      // Convert level to integer for backend
      level: speakerData.level ? parseInt(speakerData.level) : null,
      availability: speakerData.availability, // Availability is already properly formatted
    };

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

    speakerManager.updateSpeakerWithCallbacks(
      aid,
      submitData,
      (data) => {
        setAlert({
          type: "success",
          message: "Speaker updated successfully!",
        });

        setTimeout(() => {
          navigate(`/admin/speaker/${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 speaker. Please correct the following errors:",
                details: errorList,
              });
            } else {
              setAlert({
                type: "error",
                message:
                  error.general ||
                  error.message ||
                  "Failed to update speaker. Please check the form and try again.",
              });
            }
          } else {
            setAlert({
              type: "error",
              message:
                error.message ||
                error.detail ||
                "Failed to update speaker. Please try again.",
            });
          }
        } else {
          setAlert({
            type: "error",
            message: "An unexpected error occurred. Please try again.",
          });
        }

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

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

  // Skill sets tag/pill UI handlers
  const handleAddSkillSet = useCallback(() => {
    if (!currentSkillSetId || currentSkillSetId === "" || currentSkillSetId === "0") {
      return;
    }

    const skillSetDetails = skillSetOptions.find(opt => opt.value === currentSkillSetId);
    if (skillSetDetails) {
      const newSkillSet = {
        id: currentSkillSetId,
        name: skillSetDetails.label,
      };
      setSelectedSkillSets(prev => [...prev, newSkillSet]);
      setCurrentSkillSetId("");
    }
  }, [currentSkillSetId, skillSetOptions]);

  const handleRemoveSkillSet = useCallback((skillSetId) => {
    setSelectedSkillSets(prev => prev.filter(ss => ss.id !== skillSetId));
  }, []);

  const handleClearAllSkillSets = useCallback(() => {
    setSelectedSkillSets([]);
    setCurrentSkillSetId("");
  }, []);

  // Filter out already selected skill sets from dropdown
  const filteredSkillSetOptions = useMemo(() => {
    return skillSetOptions.filter(opt =>
      !selectedSkillSets.some(ss => ss.id === opt.value)
    );
  }, [skillSetOptions, selectedSkillSets]);

  // Memoize tabs array to prevent unnecessary re-renders
  const tabs = useMemo(() => [
    {
      id: "summary",
      label: "Summary",
      to: `/admin/speaker/${aid}`,
    },
    {
      id: "detail",
      label: "Full Details",
      to: `/admin/speaker/${aid}/detail`,
    },
    {
      id: "event-contracts",
      label: "Event Contracts",
      to: `/admin/speaker/${aid}/event-contracts`,
    },
    {
      id: "comments",
      label: "Comments",
      to: `/admin/speaker/${aid}/comments`,
    },
    {
      id: "attachments",
      label: "Attachments",
      to: `/admin/speaker/${aid}/attachments`,
    },
    {
      id: "more",
      label: "More",
      to: `/admin/speaker/${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 speaker 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: "Speakers", href: "/admin/speakers", icon: UserGroupIcon },
            { label: "Detail", href: `/admin/speaker/${aid}`, icon: InformationCircleIcon },
            { label: "Update", icon: PencilSquareIcon },
          ]}
          className="mb-4 sm:mb-6"
        />

        {/* Status Alerts */}
        {speaker && speaker.status === 2 && (
          <Alert
            type="info"
            message="This speaker is archived"
            icon={ArchiveBoxIcon}
            className="mb-4"
          />
        )}
        {speaker && speaker.isBanned && (
          <Alert
            type="error"
            message="This speaker 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 Speaker
            </h2>
            <Button
              variant="outline"
              onClick={() => navigate(`/admin/speaker/${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">
          {/* Inline Error Summary */}
          {Object.keys(errors).length > 0 && (
            <div className="mb-6 p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg">
              <div className="flex items-start">
                <ExclamationTriangleIcon className="w-5 h-5 text-red-500 mr-3 flex-shrink-0 mt-0.5" />
                <div className="flex-1">
                  <h3 className="text-sm font-semibold text-red-800 mb-2">
                    {Object.keys(errors).length} Error{Object.keys(errors).length > 1 ? 's' : ''} Found
                  </h3>
                  <ul className="text-sm text-red-700 space-y-1 list-disc list-inside">
                    {Object.entries(errors).map(([field, message]) => {
                      const fieldName = field
                        .replace(/_/g, " ")
                        .replace(/([A-Z])/g, " $1")
                        .replace(/^./, (str) => str.toUpperCase())
                        .trim()
                        .replace(/\s+/g, " ");
                      return (
                        <li key={field} className="ml-2">
                          <span className="font-medium">{fieldName}:</span> {message}
                        </li>
                      );
                    })}
                  </ul>
                  <p className="mt-3 text-sm text-red-600 font-medium">
                    Please scroll down and correct the highlighted fields before submitting.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Settings Section - Hidden per requirements */}
          {/* <FormCard
            title="Settings"
            icon={BuildingOfficeIcon}
            description="Configure speaker type and basic settings"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
              <FormRow columns={1}>
                <div className="max-w-xl">
                  <Select
                    label="Speaker Type"
                    value={speakerData.type}
                    onChange={(value) =>
                      handleInputChange("type", parseInt(value))
                    }
                    options={SPEAKER_TYPE_OPTIONS}
                    error={errors.type}
                    required
                  />
                </div>
              </FormRow>
            </FormSection>
          </FormCard> */}

          {/* 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 speakers */}
              {speakerData.type === "2" && (
                <FormRow columns={2}>
                  <Input
                    label="Organization Name"
                    value={speakerData.representitiveOrganizationName}
                    onChange={(value) =>
                      handleInputChange(
                        "representitiveOrganizationName",
                        value,
                      )
                    }
                    error={errors.representitiveOrganizationName}
                    required
                  />

                  <Select
                    label="Organization Type"
                    value={speakerData.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={speakerData.firstName}
                onChange={(value) => handleInputChange("firstName", value)}
                error={errors.firstName}
                required
              />

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

            <div className="mb-4 sm:mb-6">
              <Input
                label="Email"
                type="email"
                value={speakerData.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={speakerData.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={speakerData.phone}
                onChange={(value) => handleInputChange("phone", value)}
                error={errors.phone}
                required
              />

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

            {speakerData.phoneType === 2 && (
              <div className="mb-4 sm:mb-6">
                <Input
                  label="Phone Extension"
                  value={speakerData.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={speakerData.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={speakerData.otherPhone}
                onChange={(value) =>
                  handleInputChange("otherPhone", value)
                }
                error={errors.otherPhone}
              />

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

            {speakerData.otherPhoneType === 2 && (
              <div className="mb-4 sm:mb-6">
                <Input
                  label="Other Phone Extension"
                  value={speakerData.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={speakerData.hasShippingAddress}
                onChange={() => handleCheckboxChange("hasShippingAddress")}
              />
            </div>

            <div
              className={`grid ${speakerData.hasShippingAddress ? "grid-cols-1 lg:grid-cols-2" : "grid-cols-1"} gap-6 sm:gap-8`}
            >
              {/* Billing Address */}
              <div>
                {speakerData.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={speakerData.country}
                    onChange={(value) =>
                      handleInputChange("country", value)
                    }
                    error={errors.country}
                    required
                  />

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

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

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

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

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

              {/* Shipping Address */}
              {speakerData.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={speakerData.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={speakerData.shippingPhone}
                      onChange={(value) =>
                        handleInputChange("shippingPhone", value)
                      }
                      placeholder="The contact phone number for this shipping address"
                      error={errors.shippingPhone}
                      required
                    />

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

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

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

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

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

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

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

          {/* Professional Information Section */}
          <FormCard
            title="Professional Information"
            icon={BriefcaseIcon}
            description="Skills and professional details"
            maxWidth="full"
            className="mb-6"
          >
            <FormSection>
            <div className="space-y-4 sm:space-y-6">
              {/* Skill Sets - Tag/Pill UI */}
              <div>
                <Select
                  label="Skill Sets"
                  value={currentSkillSetId}
                  onChange={setCurrentSkillSetId}
                  options={filteredSkillSetOptions}
                  required={false}
                  helperText="Select a skill set to add"
                />
              </div>

              <div className="flex justify-center mt-4">
                <Button
                  type="button"
                  variant="success"
                  onClick={handleAddSkillSet}
                  disabled={!currentSkillSetId || currentSkillSetId === "" || currentSkillSetId === "0"}
                  icon={PlusIcon}
                  className="whitespace-nowrap"
                >
                  Add Skill Set
                </Button>
              </div>

              {errors.skillSets && (
                <div className="text-red-600 text-sm mt-4 mb-2 text-center">
                  {errors.skillSets}
                </div>
              )}

              {selectedSkillSets.length > 0 && (
                <div className="mt-4">
                  <div className="flex items-center justify-between mb-3">
                    <div className="text-sm font-medium opacity-90">
                      Selected Skill Sets ({selectedSkillSets.length})
                    </div>
                    {selectedSkillSets.length > 1 && (
                      <button
                        type="button"
                        onClick={handleClearAllSkillSets}
                        className="text-sm text-red-600 hover:text-red-800 underline"
                      >
                        Clear all
                      </button>
                    )}
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {selectedSkillSets.map((skillSet) => (
                      <div
                        key={skillSet.id}
                        className="inline-flex items-center gap-2 px-3 py-2 bg-blue-100 text-blue-800 rounded-full text-sm font-medium"
                      >
                        <span>{skillSet.name}</span>
                        <button
                          type="button"
                          onClick={() => handleRemoveSkillSet(skillSet.id)}
                          className="hover:bg-blue-200 rounded-full p-0.5 transition-colors"
                        >
                          <XMarkIcon className="w-4 h-4" />
                        </button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

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

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

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

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

              <Input
                label="Hourly Salary Desired"
                type="number"
                value={speakerData.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>
              <label className={`block text-sm font-medium mb-2 ${errors.availability ? 'text-red-600' : getThemeClasses('text-primary')}`}>
                Availability Schedule
                <span className="text-red-500 ml-1">*</span>
              </label>
              <p className={`text-sm sm:text-base ${getThemeClasses('text-muted')} mb-4`}>
                Select the time slots when the speaker is available
              </p>
              <div className={`overflow-x-auto ${errors.availability ? 'border-2 border-red-500 rounded-lg p-2 bg-red-50' : ''}`}>
                <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={speakerData.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={speakerData.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 speaker 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={speakerData.tags}
                onChange={(value) => handleInputChange("tags", value)}
                error={errors.tags}
                required={false}
                label="Tags (Optional)"
                helperText="Select tags to categorize this speaker"
                onUnauthorized={onUnauthorized}
              />

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

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

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

              <Textarea
                label="Additional Comment (Optional)"
                value={speakerData.additionalComment}
                onChange={(value) =>
                  handleInputChange("additionalComment", value)
                }
                rows={4}
                maxLength={638}
                helperText={`${speakerData.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={speakerData.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/speaker/${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 AdminSpeakerUpdatePage;
