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

import React, { useState, useEffect, useMemo, useCallback, memo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  PencilSquareIcon,
  ChevronLeftIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  UserIcon,
  MapPinIcon,
  BriefcaseIcon,
  ExclamationCircleIcon,
  ChartPieIcon,
  ComputerDesktopIcon,
  EllipsisHorizontalIcon,
} from "@heroicons/react/24/outline";
import {
  useStaffManager,
} from "../../../../services/Services";
import {
  TagsMultiSelect,
  SkillSetsMultiSelect,
  InsuranceRequirementsMultiSelect,
} from "../../../../components/business/selects";
import {
  STAFF_TYPE_EXECUTIVE,
  STAFF_TYPE_MANAGEMENT,
  STAFF_TYPE_FRONTLINE,
  STAFF_PHONE_TYPE_OF_OPTIONS,
  STAFF_GENDER_OTHER,
} from "../../../../constants/Staff";
import {
  GENDER_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  DetailFullView,
  FormCard,
  FormSection,
  FormRow,
  Input,
  Select,
  Checkbox,
  DateInput,
  EditButton,
  Button,
  Breadcrumb,
  PageHeader,
  Tabs,
  UIXThemeProvider,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";

// Step 2: Move static constants outside component
const STAFF_TYPE_OPTIONS = [
  { value: STAFF_TYPE_EXECUTIVE, label: "Executive" },
  { value: STAFF_TYPE_MANAGEMENT, label: "Management" },
  { value: STAFF_TYPE_FRONTLINE, label: "Frontline" },
];

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

// 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;
};

// Step 4: Create memoized content component
const AdminStaffUpdatePageContent = memo(
  function AdminStaffUpdatePageContent() {
    const { aid } = useParams();
    const navigate = useNavigate();
    const staffManager = useStaffManager();
    const { getThemeClasses } = useUIXTheme();

    // State management
    const [isLoading, setIsLoading] = useState(true);
    const [errors, setErrors] = useState({});
    const [alert, setAlert] = useState(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [staffMember, setStaffMember] = useState(null);

    // Form state
    const [staffData, setStaffData] = useState({
      type: STAFF_TYPE_FRONTLINE,
      email: "",
      phone: "",
      phoneType: 0,
      phoneExtension: "",
      firstName: "",
      lastName: "",
      otherPhone: "",
      otherPhoneType: 0,
      otherPhoneExtension: "",
      isOkToText: false,
      isOkToEmail: false,
      postalCode: "",
      addressLine1: "",
      addressLine2: "",
      city: "",
      region: "",
      country: "Canada",
      hasShippingAddress: false,
      shippingName: "",
      shippingPhone: "",
      shippingCountry: "Canada",
      shippingRegion: "",
      shippingCity: "",
      shippingAddressLine1: "",
      shippingAddressLine2: "",
      shippingPostalCode: "",
      limitSpecial: "",
      policeCheck: "",
      driversLicenseClass: "",
      vehicleTypes: [],
      skillSets: [],
      insuranceRequirements: [],
      emergencyContactName: "",
      emergencyContactRelationship: "",
      emergencyContactTelephone: "",
      emergencyContactAlternativeTelephone: "",
      description: "",
      preferredLanguage: "English",
      tags: [],
      howDidYouHearAboutUsID: "",
      isHowDidYouHearAboutUsOther: false,
      howDidYouHearAboutUsOther: "",
      joinDate: "",
      gender: 0,
      genderOther: "",
      identifyAs: [],
    });

    // Step 5: Add useMemo for theme classes
    const themeClasses = useMemo(
      () => ({
        borderPrimary: getThemeClasses("border-primary"),
        textMuted: getThemeClasses("text-muted"),
        textPrimary: getThemeClasses("text-primary"),
        cardBg: getThemeClasses("card-bg"),
        cardShadow: getThemeClasses("card-shadow"),
        inputBorder: getThemeClasses("input-border"),
        focusRing: getThemeClasses("focus-ring"),
        focusBorder: getThemeClasses("focus-border"),
        textDefault: getThemeClasses("text-default"),
        accentPrimary: getThemeClasses("accent-primary"),
        alertSuccess: getThemeClasses("alert-success"),
        alertError: getThemeClasses("alert-error"),
        textSuccessIcon: getThemeClasses("text-success-icon"),
        textErrorIcon: getThemeClasses("text-error-icon"),
        borderDefault: getThemeClasses("border-default"),
      }),
      [getThemeClasses],
    );

    // Step 6: Wrap event handlers with useCallback
    const onUnauthorized = useCallback(() => {
      navigate("/login?unauthorized=true");
    }, [navigate]);

    // Load staff detail on mount
    useEffect(() => {
      let mounted = true;

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

        setIsLoading(true);
        setErrors({});

        try {
          const response = await staffManager.getStaffDetail(
            aid,
            onUnauthorized,
          );

          if (mounted) {
            setStaffMember(response);

            const formatDateForInput = (dateValue) => {
              if (!dateValue) return "";
              try {
                const date = new Date(dateValue);
                if (isNaN(date.getTime())) return "";
                return date.toISOString().split("T")[0];
              } catch (e) {
                return "";
              }
            };

            setStaffData({
              type: response.type || STAFF_TYPE_FRONTLINE,
              email: response.email || "",
              phone: response.phone || "",
              phoneType: response.phoneType || 0,
              phoneExtension: response.phoneExtension || "",
              firstName: response.firstName || "",
              lastName: response.lastName || "",
              otherPhone: response.otherPhone || "",
              otherPhoneType: response.otherPhoneType || 0,
              otherPhoneExtension: response.otherPhoneExtension || "",
              isOkToText: response.isOkToText || false,
              isOkToEmail: response.isOkToEmail || false,
              postalCode: response.postalCode || "",
              addressLine1: response.addressLine1 || "",
              addressLine2: response.addressLine2 || "",
              city: response.city || "",
              region: response.region || "",
              country: response.country || "Canada",
              hasShippingAddress: response.hasShippingAddress || false,
              shippingName: response.shippingName || "",
              shippingPhone: response.shippingPhone || "",
              shippingCountry: response.shippingCountry || "Canada",
              shippingRegion: response.shippingRegion || "",
              shippingCity: response.shippingCity || "",
              shippingAddressLine1: response.shippingAddressLine1 || "",
              shippingAddressLine2: response.shippingAddressLine2 || "",
              shippingPostalCode: response.shippingPostalCode || "",
              limitSpecial: response.limitSpecial || "",
              policeCheck: formatDateForInput(response.policeCheck),
              driversLicenseClass: response.driversLicenseClass || "",
              vehicleTypes: response.vehicleTypes
                ? response.vehicleTypes.map((vt) => vt.id || vt)
                : [],
              skillSets: response.skillSets
                ? response.skillSets.map((ss) => ss.id || ss)
                : [],
              insuranceRequirements: response.insuranceRequirements
                ? response.insuranceRequirements.map((ir) => ir.id || ir)
                : [],
              emergencyContactName: response.emergencyContactName || "",
              emergencyContactRelationship:
                response.emergencyContactRelationship || "",
              emergencyContactTelephone:
                response.emergencyContactTelephone || "",
              emergencyContactAlternativeTelephone:
                response.emergencyContactAlternativeTelephone || "",
              description: response.description || "",
              preferredLanguage: response.preferredLanguage || "English",
              tags: response.tags
                ? response.tags.map((tag) => tag.id || tag)
                : [],
              howDidYouHearAboutUsID: response.howDidYouHearAboutUsID || "",
              isHowDidYouHearAboutUsOther:
                response.isHowDidYouHearAboutUsOther || false,
              howDidYouHearAboutUsOther:
                response.howDidYouHearAboutUsOther || "",
              joinDate: formatDateForInput(response.joinDate),
              gender: response.gender || 0,
              genderOther: response.genderOther || "",
              identifyAs: response.identifyAs || [],
            });

            setIsLoading(false);
          }
        } catch (error) {
          if (mounted) {
            if (import.meta.env.DEV) {
              console.error("Failed to fetch staff details:", error);
            }
            setAlert({
              type: "error",
              message: "Failed to load staff details. Please try again.",
            });
            setIsLoading(false);
          }
        }
      };

      fetchStaffDetail();

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

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

        if (errors[field]) {
          setErrors((prev) => ({
            ...prev,
            [field]: undefined,
          }));
        }
      },
      [errors],
    );

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

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

      if (!staffData.firstName.trim()) {
        newErrors.firstName = "First name is required";
      }
      if (!staffData.lastName.trim()) {
        newErrors.lastName = "Last name is required";
      }
      if (!staffData.email.trim()) {
        newErrors.email = "Email is required";
      }
      if (!staffData.phone.trim()) {
        newErrors.phone = "Phone number is required";
      }

      if (staffData.hasShippingAddress) {
        if (!staffData.shippingName.trim()) {
          newErrors.shippingName = "Shipping name is required";
        }
        if (!staffData.shippingPhone.trim()) {
          newErrors.shippingPhone = "Shipping phone is required";
        }
      }

      if (
        staffData.gender === STAFF_GENDER_OTHER &&
        !staffData.genderOther.trim()
      ) {
        newErrors.genderOther = "Please specify other gender";
      }

      return newErrors;
    }, [staffData]);

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

        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;
        }

        setIsSubmitting(true);
        setErrors({});

        const submitData = {
          id: aid,
          type: parseInt(staffData.type),
          firstName: staffData.firstName,
          lastName: staffData.lastName,
          email: staffData.email,
          phone: staffData.phone,
          phoneType: parseInt(staffData.phoneType),
          phoneExtension: staffData.phoneExtension,
          otherPhone: staffData.otherPhone,
          otherPhoneType: parseInt(staffData.otherPhoneType),
          otherPhoneExtension: staffData.otherPhoneExtension,
          isOkToText: staffData.isOkToText,
          isOkToEmail: staffData.isOkToEmail,
          postalCode: staffData.postalCode,
          addressLine1: staffData.addressLine1,
          addressLine2: staffData.addressLine2,
          city: staffData.city,
          region: staffData.region,
          country: staffData.country,
          hasShippingAddress: staffData.hasShippingAddress,
          shippingName: staffData.shippingName,
          shippingPhone: staffData.shippingPhone,
          shippingCountry: staffData.shippingCountry,
          shippingRegion: staffData.shippingRegion,
          shippingCity: staffData.shippingCity,
          shippingAddressLine1: staffData.shippingAddressLine1,
          shippingAddressLine2: staffData.shippingAddressLine2,
          shippingPostalCode: staffData.shippingPostalCode,
          limitSpecial: staffData.limitSpecial,
          policeCheck: staffData.policeCheck || null,
          driversLicenseClass: staffData.driversLicenseClass,
          vehicleTypes: staffData.vehicleTypes || [],
          skillSets: staffData.skillSets || [],
          insuranceRequirements: staffData.insuranceRequirements || [],
          emergencyContactName: staffData.emergencyContactName,
          emergencyContactRelationship: staffData.emergencyContactRelationship,
          emergencyContactTelephone: staffData.emergencyContactTelephone,
          emergencyContactAlternativeTelephone:
            staffData.emergencyContactAlternativeTelephone,
          description: staffData.description,
          tags: staffData.tags || [],
          gender: parseInt(staffData.gender),
          genderOther: staffData.genderOther,
          joinDate: staffData.joinDate || null,
          howDidYouHearAboutUsID: staffData.howDidYouHearAboutUsID,
          isHowDidYouHearAboutUsOther: staffData.isHowDidYouHearAboutUsOther,
          howDidYouHearAboutUsOther: staffData.howDidYouHearAboutUsOther,
          preferredLanguage: staffData.preferredLanguage,
          identifyAs: staffData.identifyAs.map((id) => parseInt(id)),
        };

        try {
          await staffManager.updateStaff(aid, submitData, onUnauthorized);

          setAlert({
            type: "success",
            message: "Staff member updated successfully!",
          });

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

          window.scrollTo(0, 0);
        } finally {
          setIsSubmitting(false);
        }
      },
      [aid, staffData, validateForm, staffManager, navigate, onUnauthorized],
    );


    // Step 7: Wrap arrays/computed values with useMemo
    const breadcrumbItems = useMemo(
      () => [
        {
          label: "Dashboard",
          to: "/admin/dashboard",
          icon: ChartBarIcon,
          hideOnMobile: false,
          mobileLabel: "Dash",
        },
        {
          label: "Staff",
          to: "/admin/staff",
          icon: UserGroupIcon,
        },
        {
          label: "Detail",
          to: `/admin/staff/${aid}`,
          icon: InformationCircleIcon,
        },
        {
          label: "Update",
          icon: PencilSquareIcon,
          isActive: true,
        },
      ],
      [aid],
    );

    const tabItems = useMemo(
      () => [
        {
          label: "Summary",
          to: `/admin/staff/${aid}`,
        },
        {
          label: "Full Details",
          to: `/admin/staff/${aid}/detail`,
        },
        {
          label: "Update",
          isActive: true,
        },
        {
          label: "Comments",
          to: `/admin/staff/${aid}/comments`,
        },
        {
          label: "Attachments",
          to: `/admin/staff/${aid}/attachments`,
        },
        {
          label: "More",
          to: `/admin/staff/${aid}/more`,
          icon: EllipsisHorizontalIcon,
        },
      ],
      [aid],
    );

    // Step 8: Replace hardcoded colors with theme classes
    if (isLoading) {
      return (
        <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">
              <div
                className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}
              ></div>
              <p
                className={`mt-4 text-sm sm:text-base ${themeClasses.textMuted}`}
              >
                Loading staff details...
              </p>
            </div>
          </div>
        </div>
      );
    }

    return (
      <div>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
          {/* Breadcrumb */}
          <Breadcrumb items={breadcrumbItems} />

          {/* Page Header */}
          <PageHeader
            icon={UserGroupIcon}
            title="Staff Member - Update"
            subtitle="Update staff member information"
          />

          {/* Tab Navigation */}
          <div
            className={`${themeClasses.cardBg} ${themeClasses.cardShadow} rounded-lg mb-6`}
          >
            <Tabs tabs={tabItems} mode="routing" />
          </div>

          {/* Form Card - Match tab navigation width */}
          <form onSubmit={handleSubmit}>
            <FormCard
              title="Update Staff Member"
              icon={PencilSquareIcon}
              maxWidth="full"
            >
              {/* Basic Information Section */}
              <FormSection title="Basic Information" icon={UserIcon}>
                <FormRow columns={2}>
                  <Select
                    label="Type"
                    value={staffData.type}
                    onChange={(value) =>
                      handleInputChange("type", parseInt(value))
                    }
                    options={STAFF_TYPE_OPTIONS}
                    error={errors.type}
                    required
                  />
                  <Input
                    label="Email"
                    type="email"
                    value={staffData.email}
                    onChange={(value) => handleInputChange("email", value)}
                    error={errors.email}
                    required
                  />
                </FormRow>

                <FormRow columns={2}>
                  <Input
                    label="First Name"
                    value={staffData.firstName}
                    onChange={(value) => handleInputChange("firstName", value)}
                    error={errors.firstName}
                    required
                  />
                  <Input
                    label="Last Name"
                    value={staffData.lastName}
                    onChange={(value) => handleInputChange("lastName", value)}
                    error={errors.lastName}
                    required
                  />
                </FormRow>

                <Checkbox
                  label="I agree to receive electronic email"
                  checked={staffData.isOkToEmail}
                  onChange={(checked) =>
                    handleInputChange("isOkToEmail", checked)
                  }
                />

                <FormRow columns={2}>
                  <Input
                    label="Phone"
                    type="tel"
                    value={staffData.phone}
                    onChange={(value) => handleInputChange("phone", value)}
                    error={errors.phone}
                    required
                  />
                  <Select
                    label="Phone Type"
                    value={staffData.phoneType}
                    onChange={(value) =>
                      handleInputChange("phoneType", parseInt(value))
                    }
                    options={STAFF_PHONE_TYPE_OF_OPTIONS}
                    error={errors.phoneType}
                  />
                </FormRow>

                {staffData.phoneType === 3 && (
                  <Input
                    label="Phone Extension"
                    value={staffData.phoneExtension}
                    onChange={(value) =>
                      handleInputChange("phoneExtension", value)
                    }
                    error={errors.phoneExtension}
                  />
                )}

                <Checkbox
                  label="I agree to receive texts to my phone"
                  checked={staffData.isOkToText}
                  onChange={(checked) =>
                    handleInputChange("isOkToText", checked)
                  }
                />

                <FormRow columns={2}>
                  <Input
                    label="Other Phone (Optional)"
                    type="tel"
                    value={staffData.otherPhone}
                    onChange={(value) => handleInputChange("otherPhone", value)}
                    error={errors.otherPhone}
                  />
                  <Select
                    label="Other Phone Type"
                    value={staffData.otherPhoneType}
                    onChange={(value) =>
                      handleInputChange("otherPhoneType", parseInt(value))
                    }
                    options={STAFF_PHONE_TYPE_OF_OPTIONS}
                    error={errors.otherPhoneType}
                  />
                </FormRow>

                {staffData.otherPhoneType === 3 && (
                  <Input
                    label="Other Phone Extension (Optional)"
                    value={staffData.otherPhoneExtension}
                    onChange={(value) =>
                      handleInputChange("otherPhoneExtension", value)
                    }
                    error={errors.otherPhoneExtension}
                  />
                )}
              </FormSection>

              {/* Address Information Section */}
              <FormSection title="Address Information" icon={MapPinIcon}>
                <Checkbox
                  label="Has mailing address different than home address"
                  checked={staffData.hasShippingAddress}
                  onChange={(checked) =>
                    handleCheckboxChange("hasShippingAddress", checked)
                  }
                />

                <div
                  className={`grid ${staffData.hasShippingAddress ? "grid-cols-1 lg:grid-cols-2" : "grid-cols-1"} gap-6`}
                >
                  {/* Home/Billing Address */}
                  <div>
                    {staffData.hasShippingAddress && (
                      <h4
                        className={`text-base font-medium ${themeClasses.textPrimary} mb-4`}
                      >
                        Home Address
                      </h4>
                    )}

                    <div className="space-y-4">
                      <Input
                        label="Country"
                        value={staffData.country}
                        onChange={(value) =>
                          handleInputChange("country", value)
                        }
                        error={errors.country}
                        required
                      />
                      <Input
                        label="Province/State"
                        value={staffData.region}
                        onChange={(value) => handleInputChange("region", value)}
                        error={errors.region}
                        required
                      />
                      <Input
                        label="City"
                        value={staffData.city}
                        onChange={(value) => handleInputChange("city", value)}
                        error={errors.city}
                        required
                      />
                      <Input
                        label="Address Line 1"
                        value={staffData.addressLine1}
                        onChange={(value) =>
                          handleInputChange("addressLine1", value)
                        }
                        error={errors.addressLine1}
                        required
                      />
                      <Input
                        label="Address Line 2 (Optional)"
                        value={staffData.addressLine2}
                        onChange={(value) =>
                          handleInputChange("addressLine2", value)
                        }
                        error={errors.addressLine2}
                      />
                      <Input
                        label="Postal Code"
                        value={staffData.postalCode}
                        onChange={(value) =>
                          handleInputChange("postalCode", value)
                        }
                        error={errors.postalCode}
                        required
                      />
                    </div>
                  </div>

                  {/* Shipping Address */}
                  {staffData.hasShippingAddress && (
                    <div>
                      <h4
                        className={`text-base font-medium ${themeClasses.textPrimary} mb-4`}
                      >
                        Shipping Address
                      </h4>

                      <div className="space-y-4">
                        <Input
                          label="Name"
                          value={staffData.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={staffData.shippingPhone}
                          onChange={(value) =>
                            handleInputChange("shippingPhone", value)
                          }
                          placeholder="The contact phone number for this shipping address"
                          error={errors.shippingPhone}
                          required
                        />
                        <Input
                          label="Country"
                          value={staffData.shippingCountry}
                          onChange={(value) =>
                            handleInputChange("shippingCountry", value)
                          }
                          error={errors.shippingCountry}
                          required
                        />
                        <Input
                          label="Province/State"
                          value={staffData.shippingRegion}
                          onChange={(value) =>
                            handleInputChange("shippingRegion", value)
                          }
                          error={errors.shippingRegion}
                          required
                        />
                        <Input
                          label="City"
                          value={staffData.shippingCity}
                          onChange={(value) =>
                            handleInputChange("shippingCity", value)
                          }
                          error={errors.shippingCity}
                          required
                        />
                        <Input
                          label="Address Line 1"
                          value={staffData.shippingAddressLine1}
                          onChange={(value) =>
                            handleInputChange("shippingAddressLine1", value)
                          }
                          error={errors.shippingAddressLine1}
                          required
                        />
                        <Input
                          label="Address Line 2 (Optional)"
                          value={staffData.shippingAddressLine2}
                          onChange={(value) =>
                            handleInputChange("shippingAddressLine2", value)
                          }
                          error={errors.shippingAddressLine2}
                        />
                        <Input
                          label="Postal Code"
                          value={staffData.shippingPostalCode}
                          onChange={(value) =>
                            handleInputChange("shippingPostalCode", value)
                          }
                          error={errors.shippingPostalCode}
                          required
                        />
                      </div>
                    </div>
                  )}
                </div>
              </FormSection>

              {/* Additional Information Section */}
              <FormSection title="Additional Information" icon={BriefcaseIcon}>
                <div className="space-y-6">
                  <div>
                    <textarea
                      value={staffData.limitSpecial}
                      onChange={(e) =>
                        handleInputChange("limitSpecial", e.target.value)
                      }
                      rows={4}
                      className={`block w-full px-3 py-2 border ${themeClasses.inputBorder} rounded-lg ${themeClasses.focusRing} ${themeClasses.focusBorder}`}
                      maxLength={638}
                      placeholder="Limitation or Special Consideration"
                    />
                    <p className={`mt-1 text-sm ${themeClasses.textMuted}`}>
                      Max 638 characters
                    </p>
                  </div>

                  <FormRow columns={2}>
                    <DateInput
                      label="Police Check Expiry"
                      value={staffData.policeCheck}
                      onChange={(value) =>
                        handleInputChange("policeCheck", value)
                      }
                      error={errors.policeCheck}
                    />
                  </FormRow>
                </div>
              </FormSection>

              {/* Emergency Contact Section */}
              <FormSection
                title="Emergency Contact"
                icon={ExclamationCircleIcon}
              >
                <FormRow columns={2}>
                  <Input
                    label="Contact Name (Optional)"
                    value={staffData.emergencyContactName}
                    onChange={(value) =>
                      handleInputChange("emergencyContactName", value)
                    }
                    error={errors.emergencyContactName}
                  />
                  <Input
                    label="Contact Relationship (Optional)"
                    value={staffData.emergencyContactRelationship}
                    onChange={(value) =>
                      handleInputChange("emergencyContactRelationship", value)
                    }
                    error={errors.emergencyContactRelationship}
                  />
                </FormRow>

                <FormRow columns={2}>
                  <Input
                    label="Contact Telephone (Optional)"
                    type="tel"
                    value={staffData.emergencyContactTelephone}
                    onChange={(value) =>
                      handleInputChange("emergencyContactTelephone", value)
                    }
                    error={errors.emergencyContactTelephone}
                  />
                  <Input
                    label="Contact Alternative Telephone (Optional)"
                    type="tel"
                    value={staffData.emergencyContactAlternativeTelephone}
                    onChange={(value) =>
                      handleInputChange(
                        "emergencyContactAlternativeTelephone",
                        value,
                      )
                    }
                    error={errors.emergencyContactAlternativeTelephone}
                  />
                </FormRow>
              </FormSection>

              {/* Metrics Section */}
              <FormSection title="Metrics" icon={ChartPieIcon}>
                <TagsMultiSelect
                  value={staffData.tags}
                  onChange={(value) => handleInputChange("tags", value)}
                  error={errors.tags}
                  required={false}
                  label="Tags (Optional)"
                  onUnauthorized={onUnauthorized}
                />

                <FormRow columns={2}>
                  <Select
                    label="Gender"
                    value={staffData.gender}
                    onChange={(value) =>
                      handleInputChange("gender", parseInt(value))
                    }
                    options={GENDER_OPTIONS}
                    error={errors.gender}
                  />
                </FormRow>

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

                <DateInput
                  label="Join Date (Optional)"
                  value={staffData.joinDate}
                  onChange={(value) => handleInputChange("joinDate", value)}
                  error={errors.joinDate}
                />
              </FormSection>

              {/* System Information Section */}
              <FormSection icon={ComputerDesktopIcon}>
                <div className="space-y-6">
                  <div className="max-w-xl">
                    <Select
                      label="Preferred Language"
                      value={staffData.preferredLanguage}
                      onChange={(value) =>
                        handleInputChange("preferredLanguage", value)
                      }
                      options={LANGUAGE_OPTIONS}
                      error={errors.preferredLanguage}
                    />
                  </div>
                </div>
              </FormSection>

              {/* Alert Display */}
              {alert && (
                <div
                  className={`p-4 rounded-lg mb-6 ${
                    alert.type === "success"
                      ? themeClasses.alertSuccess
                      : themeClasses.alertError
                  }`}
                >
                  <div className="flex items-start">
                    <div className="flex-shrink-0">
                      {alert.type === "success" ? (
                        <CheckCircleIcon
                          className={`h-5 w-5 ${themeClasses.textSuccessIcon}`}
                        />
                      ) : (
                        <ExclamationTriangleIcon
                          className={`h-5 w-5 ${themeClasses.textErrorIcon}`}
                        />
                      )}
                    </div>
                    <div className="ml-3">
                      <p className="text-sm font-medium">{alert.message}</p>
                      {alert.details && Array.isArray(alert.details) && (
                        <ul className="mt-2 text-sm list-disc list-inside">
                          {alert.details.map((detail, index) => (
                            <li key={index}>{detail}</li>
                          ))}
                        </ul>
                      )}
                    </div>
                    <div className="ml-auto pl-3">
                      <button
                        type="button"
                        onClick={() => setAlert(null)}
                        className={`${themeClasses.textMuted} hover:${themeClasses.textDefault}`}
                      >
                        <span className="sr-only">Close</span>
                        <svg
                          className="h-5 w-5"
                          viewBox="0 0 20 20"
                          fill="currentColor"
                        >
                          <path
                            fillRule="evenodd"
                            d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
                            clipRule="evenodd"
                          />
                        </svg>
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* Submit Button */}
              <div
                className={`flex justify-between items-center pt-6 border-t ${themeClasses.borderDefault}`}
              >
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate(`/admin/staff/${aid}`)}
                  icon={ChevronLeftIcon}
                >
                  Back to Detail
                </Button>

                <Button
                  type="submit"
                  variant="primary"
                  disabled={isSubmitting}
                  icon={CheckCircleIcon}
                >
                  {isSubmitting ? "Saving..." : "Save Changes"}
                </Button>
              </div>
            </FormCard>
          </form>
        </div>
      </div>
    );
  },
);

// Step 3: Wrap main export with UIXThemeProvider
function AdminStaffUpdatePage() {
  return (
    <UIXThemeProvider>
      <AdminStaffUpdatePageContent />
    </UIXThemeProvider>
  );
}

export default AdminStaffUpdatePage;
