// File Path: monorepo/web/frontend/src/pages/Admin/Facilitator/Detail/FullPage.jsx

import React, { useState, useEffect, useMemo, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  UserGroupIcon,
  InformationCircleIcon,
  ChevronLeftIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  BuildingOfficeIcon,
  HomeIcon,
  CheckCircleIcon,
  XCircleIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  UserIcon,
  BriefcaseIcon,
  ExclamationTriangleIcon,
  ChartPieIcon,
  ComputerDesktopIcon,
  CalendarIcon,
  ClockIcon,
  AcademicCapIcon,
  PencilSquareIcon,
  NoSymbolIcon,
} from "@heroicons/react/24/outline";
import {
  useFacilitatorManager,
  useAuthManager,
} from "../../../../services/Services";
import { DetailFullView, useUIXTheme } from "../../../../components/UIX";
import {
  HowHearAboutUsDisplay,
  VehicleTypesDisplay,
  TagsDisplay,
  SkillSetsDisplay,
  ServiceFeeDisplay,
  InsuranceRequirementsDisplay,
  CertificationDisplay,
} from "../../../../components/business/displays";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";

// Constants
const REPRESENTATIVE_FACILITATOR_TYPE_OF_ID = 2;
const INDIVIDUAL_FACILITATOR_TYPE_OF_ID = 1;
const FACILITATOR_PHONE_TYPE_WORK = 2;
const FACILITATOR_IS_JOB_SEEKER_YES = 1;
const FACILITATOR_IS_JOB_SEEKER_NO = 2;
const FACILITATOR_STATUS_IN_COUNTRY_OTHER = 1;
const FACILITATOR_STATUS_IN_COUNTRY_PERMANENT_RESIDENT = 2;
const FACILITATOR_STATUS_IN_COUNTRY_NATURALIZED_CANADIAN_CITIZEN = 3;
const FACILITATOR_STATUS_IN_COUNTRY_PROTECTED_PERSONS = 4;
const FACILITATOR_MARITAL_STATUS_OTHER = 1;
const FACILITATOR_ACCOMPLISHED_EDUCATION_OTHER = 1;

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

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

const FACILITATOR_ORGANIZATION_TYPE_OPTIONS = {
  1: "Educational",
  2: "Private/Corporation",
  3: "Non-profit",
  4: "Government",
};

const GENDER_OPTIONS = {
  1: "Other",
  2: "Male",
  3: "Female",
  4: "Prefer not to say",
};

const PHONE_TYPE_OPTIONS = {
  1: "Mobile",
  2: "Work",
  3: "Home",
};

const FACILITATOR_STATUS_IN_COUNTRY_OPTIONS = {
  1: "Other",
  2: "Permanent Resident",
  3: "Naturalized Canadian Citizen",
  4: "Protected Persons",
};

const FACILITATOR_MARITAL_STATUS_OPTIONS = {
  1: "Other",
  2: "Single",
  3: "Married",
  4: "Divorced",
  5: "Widowed",
};

const FACILITATOR_ACCOMPLISHED_EDUCATION_OPTIONS = {
  1: "Other",
  2: "No formal education",
  3: "Elementary school",
  4: "High school",
  5: "College",
  6: "University",
  7: "Graduate school",
};

const IDENTIFY_AS_OPTIONS = {
  1: "Aboriginal",
  2: "Visible minority",
  3: "Person with disability",
  4: "Youth",
  5: "Senior",
  6: "Woman",
  7: "Newcomer",
};

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

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [facilitator, setFacilitator] = useState(null);

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

  // Stable navigation callbacks
  const handleBackToFacilitators = useCallback(() => {
    navigate("/admin/facilitators");
  }, [navigate]);

  const handleEditFacilitator = useCallback(() => {
    navigate(`/admin/facilitator/${aid}/edit`);
  }, [navigate, aid]);

  const handleErrorClose = useCallback(() => {
    setErrors({});
  }, []);

  // Fetch facilitator detail
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }

    const fetchFacilitatorDetail = async () => {
      if (!aid) {
        setErrors({ general: "Facilitator ID is required" });
        setFetching(false);
        return;
      }

      try {
        setFetching(true);
        setErrors({});

        const response = await facilitatorManager.getFacilitatorDetail(
          aid,
          onUnauthorized,
        );
        setFacilitator(response);
      } catch (error) {
        console.error("Failed to fetch facilitator detail:", error);
        setErrors(error);
      } finally {
        setFetching(false);
      }
    };

    fetchFacilitatorDetail();
  }, [aid, facilitatorManager, authManager]);

  // Helper function to get facilitator display name
  const getFacilitatorDisplayName = useCallback((facilitator) => {
    if (!facilitator) return "Facilitator";
    if (facilitator.name) return facilitator.name;
    const fullName =
      `${facilitator.firstName || ""} ${facilitator.lastName || ""}`.trim();
    return fullName || "Facilitator";
  }, []);

  const formatPhone = useCallback((phone, extension = null) => {
    if (!phone) return "-";
    const formatted = phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    return extension ? `${formatted} ext. ${extension}` : formatted;
  }, []);

  // Format level badge
  const formatLevel = useCallback(
    (level) => {
      // Find the level option that matches the value
      const levelOption = FACILITATOR_LEVEL_OPTIONS.find(
        (opt) => opt.value === level,
      );
      const levelText = levelOption ? levelOption.label : "Not Set";

      let variant = "secondary";

      switch (level) {
        case FACILITATOR_LEVEL_IN_TRAINING:
          variant = "info";
          break;
        case FACILITATOR_LEVEL_SECONDARY_FACILITATOR:
          variant = "info";
          break;
        case FACILITATOR_LEVEL_LEAD_FACILITATOR:
          variant = "info";
          break;
        case FACILITATOR_LEVEL_TRAINER:
          variant = "primary";
          break;
      }

      return (
        <span
          className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs sm:text-sm font-medium ${getThemeClasses(`badge.${variant}`)}`}
        >
          <AcademicCapIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
          {levelText}
        </span>
      );
    },
    [getThemeClasses],
  );

  // Format availability display
  const formatAvailability = useCallback(
    (availability) => {
      if (!availability || typeof availability !== "object") {
        return (
          <span
            className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs sm:text-sm font-medium ${getThemeClasses("badge.secondary")}`}
          >
            <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            Not Set
          </span>
        );
      }

      // Build a list of available time slots
      const availableSlots = [];
      const days = [
        "monday",
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
        "sunday",
      ];
      const dayLabels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

      days.forEach((day, index) => {
        if (availability[day]) {
          if (availability[day].am && availability[day].pm) {
            availableSlots.push(`${dayLabels[index]} (All Day)`);
          } else if (availability[day].am) {
            availableSlots.push(`${dayLabels[index]} (AM)`);
          } else if (availability[day].pm) {
            availableSlots.push(`${dayLabels[index]} (PM)`);
          }
        }
      });

      if (availableSlots.length === 0) {
        return (
          <span
            className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs sm:text-sm font-medium ${getThemeClasses("badge.secondary")}`}
          >
            <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
            No Availability Set
          </span>
        );
      }

      // Return a formatted display
      return (
        <div className="space-y-1">
          {availableSlots.map((slot, index) => (
            <span
              key={index}
              className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs sm:text-sm font-medium ${getThemeClasses("badge.primary")} mr-2 mb-1`}
            >
              <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
              {slot}
            </span>
          ))}
        </div>
      );
    },
    [getThemeClasses],
  );

  // FIXED: Enhanced formatDriversLicenseClasses to handle various input types
  const formatDriversLicenseClasses = useCallback((driversLicenseClass) => {
    // Handle null/undefined
    if (!driversLicenseClass) return "-";

    // If it's a string, return it as is
    if (typeof driversLicenseClass === "string") {
      return driversLicenseClass || "-";
    }

    // If it's an array
    if (Array.isArray(driversLicenseClass)) {
      if (driversLicenseClass.length === 0) return "-";

      // Extract text from each item and join
      return (
        driversLicenseClass
          .map((license) => {
            // Handle if license is a string
            if (typeof license === "string") return license;
            // Handle if license is an object with text property
            if (license && typeof license === "object") {
              return (
                license.text ||
                license.label ||
                license.name ||
                license.value ||
                ""
              );
            }
            return "";
          })
          .filter(Boolean) // Remove empty strings
          .join(", ") || "-"
      );
    }

    // If it's a single object (not an array)
    if (typeof driversLicenseClass === "object") {
      return (
        driversLicenseClass.text ||
        driversLicenseClass.label ||
        driversLicenseClass.name ||
        driversLicenseClass.value ||
        "-"
      );
    }

    // Fallback for any other type
    return String(driversLicenseClass) || "-";
  }, []);

  const formatMultiSelect = useCallback((selectedValues, options) => {
    if (!selectedValues || selectedValues.length === 0) return "-";
    return selectedValues
      .map((value) => options[value] || `Unknown (${value})`)
      .join(", ");
  }, []);

  const formatAddress = useCallback((facilitator) => {
    if (!facilitator) return "-";
    const address =
      facilitator.fullAddressWithPostalCode ||
      `${facilitator.addressLine1 || ""} ${facilitator.city || ""} ${facilitator.region || ""} ${facilitator.postalCode || ""}`.trim();

    return address || "-";
  }, []);

  // Extract IDs from array of objects
  const extractIds = useCallback((items) => {
    if (!items || !Array.isArray(items)) return [];
    return items.map((item) => item.id || item.value).filter(Boolean);
  }, []);

  // Configure DetailFullView props
  const breadcrumbItems = useMemo(
    () => [
      {
        label: "Dashboard",
        to: "/admin/dashboard",
        icon: HomeIcon,
      },
      {
        label: "Facilitators",
        to: "/admin/facilitators",
        icon: UserGroupIcon,
      },
      {
        label: "Full Details",
        icon: InformationCircleIcon,
        isActive: true,
      },
    ],
    [],
  );

  const headerConfig = useMemo(
    () => ({
      title: "Facilitator - Full Details",
      icon: UserGroupIcon,
      loadingText: "Loading facilitator details...",
      notFoundTitle: "Facilitator Not Found",
      notFoundMessage:
        "The facilitator you're looking for doesn't exist or you don't have permission to view it.",
      notFoundAction: {
        label: "Back to Facilitators",
        icon: ChevronLeftIcon,
        onClick: handleBackToFacilitators,
      },
    }),
    [handleBackToFacilitators],
  );

  const actionButtons = useMemo(
    () => [
      {
        variant: "outline",
        onClick: handleBackToFacilitators,
        icon: ChevronLeftIcon,
        label: "Back",
      },
      {
        variant: "secondary",
        onClick: handleEditFacilitator,
        icon: PencilSquareIcon,
        label: "Edit",
      },
    ],
    [handleBackToFacilitators, handleEditFacilitator],
  );

  const tabs = useMemo(
    () => [
      {
        label: "Summary",
        to: `/admin/facilitator/${aid}`,
      },
      {
        label: "Full Details",
        isActive: true,
      },
      {
        label: "Event Contracts",
        to: `/admin/facilitator/${aid}/event-contracts`,
      },
      {
        label: "Comments",
        to: `/admin/facilitator/${aid}/comments`,
      },
      {
        label: "Attachments",
        to: `/admin/facilitator/${aid}/attachments`,
      },
      {
        label: "More",
        to: `/admin/facilitator/${aid}/more`,
        icon: EllipsisHorizontalIcon,
      },
    ],
    [aid],
  );

  const mainInfoCard = useMemo(
    () => ({
      title: "Facilitator Information",
      icon: UserGroupIcon,
      primarySections: [
        {
          component: (
            <div className="space-y-4">
              <div>
                <h3
                  className={`text-lg font-semibold ${getThemeClasses("text.primary")}`}
                >
                  {getFacilitatorDisplayName(facilitator)}
                </h3>
              </div>

              {facilitator?.email && (
                <div
                  className={`flex items-center ${getThemeClasses("text.secondary")}`}
                >
                  <EnvelopeIcon className="w-4 h-4 mr-2" />
                  <a
                    href={`mailto:${facilitator.email}`}
                    className={getThemeClasses("text.link")}
                  >
                    {facilitator.email}
                  </a>
                </div>
              )}

              {facilitator?.phone && (
                <div
                  className={`flex items-center ${getThemeClasses("text.secondary")}`}
                >
                  <PhoneIcon className="w-4 h-4 mr-2" />
                  <a
                    href={`tel:${facilitator.phone}`}
                    className={getThemeClasses("text.link")}
                  >
                    {formatPhone(
                      facilitator.phone,
                      facilitator.phoneType === FACILITATOR_PHONE_TYPE_WORK
                        ? facilitator.phoneExtension
                        : null,
                    )}
                  </a>
                </div>
              )}

              {facilitator?.otherPhone && (
                <div
                  className={`flex items-center ${getThemeClasses("text.secondary")}`}
                >
                  <PhoneIcon className="w-4 h-4 mr-2" />
                  <span>Other: </span>
                  <a
                    href={`tel:${facilitator.otherPhone}`}
                    className={`${getThemeClasses("text.link")} ml-1`}
                  >
                    {formatPhone(
                      facilitator.otherPhone,
                      facilitator.otherPhoneType === FACILITATOR_PHONE_TYPE_WORK
                        ? facilitator.otherPhoneExtension
                        : null,
                    )}
                  </a>
                </div>
              )}
            </div>
          ),
        },
      ],
      secondarySections: [
        {
          component: (
            <div className="space-y-4">
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  Type
                </label>
                <p
                  className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                >
                  {FACILITATOR_TYPE_OPTIONS[facilitator?.type] ||
                    facilitator?.type ||
                    "Not specified"}
                </p>
              </div>

              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  Level
                </label>
                <div className="mt-1">{formatLevel(facilitator?.level)}</div>
              </div>

              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  Created
                </label>
                <p
                  className={`text-base ${getThemeClasses("text.primary")} mt-1 flex items-center`}
                >
                  <CalendarIcon className="w-4 h-4 mr-1" />
                  {formatDateTime(facilitator?.createdAt)}
                </p>
              </div>
            </div>
          ),
        },
      ],
    }),
    [
      facilitator,
      getFacilitatorDisplayName,
      formatPhone,
      formatLevel,
      getThemeClasses,
    ],
  );

  const contentSections = useMemo(
    () => [
      // Organization Information (for Representative facilitators)
      ...(facilitator?.type === REPRESENTATIVE_FACILITATOR_TYPE_OF_ID
        ? [
            {
              type: "infoCard",
              title: "Organization Information",
              icon: BuildingOfficeIcon,
              primarySections: [
                {
                  component: facilitator && (
                    <div className="space-y-3">
                      <div>
                        <label
                          className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                        >
                          Organization Name
                        </label>
                        <p
                          className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                        >
                          {facilitator.representitiveOrganizationName ||
                            "Not provided"}
                        </p>
                      </div>
                      <div>
                        <label
                          className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                        >
                          Organization Type
                        </label>
                        <p
                          className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                        >
                          {FACILITATOR_ORGANIZATION_TYPE_OPTIONS[
                            facilitator.representitiveOrganizationType
                          ] || "Not provided"}
                        </p>
                      </div>
                    </div>
                  ),
                },
              ],
              showAvatar: false,
              twoColumn: false,
            },
          ]
        : []),

      {
        type: "infoCard",
        title: "Personal Information",
        icon: UserIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      First Name
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.firstName || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Last Name
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.lastName || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Gender
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.gender ? (
                        <>
                          {GENDER_OPTIONS[facilitator.gender] || "Unknown"}
                          {facilitator.gender === 1 &&
                            facilitator.genderOther &&
                            ` - ${facilitator.genderOther}`}
                        </>
                      ) : (
                        "Not provided"
                      )}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Description
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.description || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Availability
                    </label>
                    <div className="mt-1">
                      {formatAvailability(facilitator.availability)}
                    </div>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Address Information",
        icon: MapPinIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="space-y-3">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Full Address
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {facilitator.fullAddressUrl ? (
                      <a
                        href={facilitator.fullAddressUrl}
                        target="_blank"
                        rel="noreferrer"
                        className={`${getThemeClasses("text.link")} break-words`}
                      >
                        {formatAddress(facilitator)}
                      </a>
                    ) : (
                      formatAddress(facilitator)
                    )}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Contact Information",
        icon: PhoneIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Phone Type
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {PHONE_TYPE_OPTIONS[facilitator.phoneType] ||
                        "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Other Phone Type
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {PHONE_TYPE_OPTIONS[facilitator.otherPhoneType] ||
                        "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      I agree to receive electronic email
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.isOkToEmail ? (
                        <span className="inline-flex items-center text-green-700">
                          <CheckCircleIcon className="w-4 h-4 mr-1" />
                          Yes
                        </span>
                      ) : (
                        <span className="inline-flex items-center text-red-700">
                          <XCircleIcon className="w-4 h-4 mr-1" />
                          No
                        </span>
                      )}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      I agree to receive texts to my phone
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.isOkToText ? (
                        <span className="inline-flex items-center text-green-700">
                          <CheckCircleIcon className="w-4 h-4 mr-1" />
                          Yes
                        </span>
                      ) : (
                        <span className="inline-flex items-center text-red-700">
                          <XCircleIcon className="w-4 h-4 mr-1" />
                          No
                        </span>
                      )}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Professional Details",
        icon: BriefcaseIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <TagsDisplay
                    values={extractIds(facilitator.tags)}
                    onUnauthorized={onUnauthorized}
                  />
                  <SkillSetsDisplay
                    values={extractIds(facilitator.skillSets)}
                    onUnauthorized={onUnauthorized}
                  />
                  <CertificationDisplay
                    values={extractIds(facilitator.certifications)}
                    onUnauthorized={onUnauthorized}
                  />
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Hourly rate
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.hourlySalaryDesired
                        ? `${facilitator.hourlySalaryDesired} / hr`
                        : "Not provided"}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <InsuranceRequirementsDisplay
                    values={extractIds(facilitator.insuranceRequirements)}
                    onUnauthorized={onUnauthorized}
                  />
                  {facilitator.serviceFeeId && (
                    <ServiceFeeDisplay
                      value={facilitator.serviceFeeId}
                      onUnauthorized={onUnauthorized}
                      showAmount={true}
                    />
                  )}
                  <VehicleTypesDisplay
                    values={extractIds(facilitator.vehicleTypes)}
                    onUnauthorized={onUnauthorized}
                  />
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Drivers license class(es)
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDriversLicenseClasses(
                        facilitator.driversLicenseClass,
                      )}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Preferred Language
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.preferredLanguage || "English"}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Insurance & Compliance",
        icon: CheckCircleIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Commercial insurance expiry date
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateForDisplay(
                        facilitator.commercialInsuranceExpiryDate,
                      ) || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Auto Insurance Expiry Date
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateForDisplay(
                        facilitator.autoInsuranceExpiryDate,
                      ) || "Not provided"}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      WSIB #
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.wsibNumber || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      WSIB Insurance Date
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateForDisplay(facilitator.wsibInsuranceDate) ||
                        "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Police check date
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateForDisplay(facilitator.policeCheck) ||
                        "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      HST #
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.taxId || "Not provided"}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Emergency Contact",
        icon: ExclamationTriangleIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Name
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {facilitator.emergencyContactName || "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Relationship
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {facilitator.emergencyContactRelationship || "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Telephone
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatPhone(facilitator.emergencyContactTelephone) ||
                      "Not provided"}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Internal Metrics",
        icon: ChartPieIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Do you identify as belonging to any of the following groups?
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatMultiSelect(
                      facilitator.identifyAs,
                      IDENTIFY_AS_OPTIONS,
                    ) || "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Join date
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatDateTime(facilitator.joinDate) || "Not provided"}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "System Information",
        icon: ComputerDesktopIcon,
        primarySections: [
          {
            component: facilitator && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      ID
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      <span
                        className={`font-mono text-xs sm:text-sm ${getThemeClasses("background.muted")} px-2 py-1 rounded break-all`}
                      >
                        {facilitator.publicId ||
                          facilitator.id ||
                          "Not available"}
                      </span>
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Created at
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateTime(facilitator.createdAt) || "Not available"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Created by
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.createdByUserName || "Not available"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Created from
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.createdFromIpAddress ? (
                        <span className="font-mono text-xs sm:text-sm break-all">
                          {facilitator.createdFromIpAddress}
                        </span>
                      ) : (
                        "Not available"
                      )}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Is active
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      <span
                        className={`inline-flex items-center px-2 sm:px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          facilitator.status === 1
                            ? getThemeClasses("badge.primary")
                            : getThemeClasses("badge.secondary")
                        }`}
                      >
                        {facilitator.status === 1 ? "Active" : "Archive"}
                      </span>
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Modified at
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatDateTime(facilitator.modifiedAt) ||
                        "Not available"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Modified by
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.modifiedByUserName || "Not available"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Modified from
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {facilitator.modifiedFromIpAddress ? (
                        <span className="font-mono text-xs sm:text-sm break-all">
                          {facilitator.modifiedFromIpAddress}
                        </span>
                      ) : (
                        "Not available"
                      )}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ],
    [
      facilitator,
      extractIds,
      onUnauthorized,
      formatAvailability,
      formatLevel,
      formatDriversLicenseClasses,
      formatMultiSelect,
      formatAddress,
      formatPhone,
      getThemeClasses,
    ],
  );

  const alerts = useMemo(
    () => ({
      archived: {
        message: "This facilitator is archived",
        icon: ArchiveBoxIcon,
      },
      banned: {
        message: "This facilitator is banned",
        icon: NoSymbolIcon,
      },
    }),
    [],
  );

  return (
    <DetailFullView
      entityData={facilitator}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      mainInfoCard={mainInfoCard}
      contentSections={contentSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching}
      error={
        errors && typeof errors === "object" && Object.keys(errors).length > 0
          ? Object.entries(errors)
              .map(
                ([key, value]) =>
                  `${key}: ${Array.isArray(value) ? value.join(", ") : value}`,
              )
              .join("; ")
          : null
      }
      onErrorClose={handleErrorClose}
    />
  );
}

export default AdminFacilitatorDetailFullPage;
