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

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

import {
  SPEAKER_STATUS_ACTIVE,
  SPEAKER_GENDER_OPTIONS_WITH_EMPTY_OPTIONS,
  SPEAKER_IDENTIFY_AS_OPTIONS,
  SPEAKER_STATUS_IN_COUNTRY_OPTIONS_WITH_EMPTY_OPTIONS,
  SPEAKER_MARITAL_STATUS_OPTIONS_WITH_EMPTY_OPTIONS,
  SPEAKER_ACCOMPLISHED_EDUCATION_OPTIONS_WITH_EMPTY_OPTIONS,
  SPEAKER_PHONE_TYPE_OF_OPTIONS,
  SPEAKER_LEVEL_BEGINNER,
  SPEAKER_LEVEL_INTERMEDIATE,
  SPEAKER_LEVEL_ADVANCED,
  SPEAKER_LEVEL_EXPERT,
  SPEAKER_LEVEL_OPTIONS,
} from "../../../../constants/Speaker";

// Speaker Type Constants
const REPRESENTATIVE_SPEAKER_TYPE_OF_ID = 2;
const INDIVIDUAL_SPEAKER_TYPE_OF_ID = 1;
const SPEAKER_PHONE_TYPE_WORK = 2;

// Option mappings for display
const SPEAKER_TYPE_OPTIONS = {
  1: "Individual",
  2: "Representative",
};

const SPEAKER_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 IDENTIFY_AS_OPTIONS = {
  1: "Aboriginal",
  2: "Visible minority",
  3: "Person with disability",
  4: "Youth",
  5: "Senior",
  6: "Woman",
  7: "Newcomer",
};

function AdminSpeakerFullDetailPage() {
  const { id } = useParams();
  const navigate = useNavigate();
  const speakerManager = useSpeakerManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

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

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

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

  const handleEditSpeaker = useCallback(() => {
    navigate(`/admin/speaker/${id}/edit`);
  }, [navigate, id]);

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

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

    const fetchSpeakerDetail = async () => {
      if (!id) {
        setErrors({ general: "Speaker ID is required" });
        setFetching(false);
        return;
      }

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

        const response = await speakerManager.getSpeakerDetail(
          id,
          onUnauthorized,
        );
        setSpeaker(response);
      } catch (error) {
        setErrors(error);
      } finally {
        setFetching(false);
      }
    };

    fetchSpeakerDetail();
  }, [id, speakerManager, authManager, onUnauthorized, navigate]);

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

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

  const formatAddress = useCallback((speaker) => {
    if (!speaker) return "-";
    const parts = [
      speaker.addressLine1,
      speaker.addressLine2,
      speaker.city,
      speaker.region,
      speaker.postalCode,
      speaker.country,
    ].filter(Boolean);
    return parts.length > 0 ? parts.join(", ") : "-";
  }, []);

  const getTagIds = useCallback((tags) => {
    if (!tags || tags.length === 0) return [];
    if (typeof tags[0] === "number" || typeof tags[0] === "string") {
      return tags;
    }
    if (tags[0].id !== undefined) {
      return tags.map((tag) => tag.id);
    }
    if (tags[0].value !== undefined) {
      return tags.map((tag) => tag.value);
    }
    return [];
  }, []);

  const getSkillSetIds = useCallback((skillSets) => {
    if (!skillSets || skillSets.length === 0) return [];
    if (typeof skillSets[0] === "number" || typeof skillSets[0] === "string") {
      return skillSets;
    }
    if (skillSets[0].id !== undefined) {
      return skillSets.map((skill) => skill.id);
    }
    if (skillSets[0].value !== undefined) {
      return skillSets.map((skill) => skill.value);
    }
    return [];
  }, []);

  const getCertificationIds = useCallback((certifications) => {
    if (!certifications || certifications.length === 0) return [];
    if (
      typeof certifications[0] === "number" ||
      typeof certifications[0] === "string"
    ) {
      return certifications;
    }
    if (certifications[0].id !== undefined) {
      return certifications.map((cert) => cert.id);
    }
    if (certifications[0].value !== undefined) {
      return certifications.map((cert) => cert.value);
    }
    return [];
  }, []);

  const getSpecializationIds = useCallback((specializations) => {
    if (!specializations || specializations.length === 0) return [];
    if (
      typeof specializations[0] === "number" ||
      typeof specializations[0] === "string"
    ) {
      return specializations;
    }
    if (specializations[0].id !== undefined) {
      return specializations.map((spec) => spec.id);
    }
    if (specializations[0].value !== undefined) {
      return specializations.map((spec) => spec.value);
    }
    return [];
  }, []);

  // Format level badge
  const formatLevel = useCallback(
    (level) => {
      const levelOption = SPEAKER_LEVEL_OPTIONS.find(
        (opt) => opt.value === level,
      );
      const levelText = levelOption ? levelOption.label : "Not Set";

      let variant = "secondary";

      switch (level) {
        case SPEAKER_LEVEL_BEGINNER:
          variant = "info";
          break;
        case SPEAKER_LEVEL_INTERMEDIATE:
          variant = "warning";
          break;
        case SPEAKER_LEVEL_ADVANCED:
          variant = "info";
          break;
        case SPEAKER_LEVEL_EXPERT:
          variant = "success";
          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>
        );
      }

      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 (
        <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.success")} mr-2 mb-1`}
            >
              <ClockIcon className="w-3 sm:w-4 h-3 sm:h-4 mr-1" />
              {slot}
            </span>
          ))}
        </div>
      );
    },
    [getThemeClasses],
  );

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

    if (typeof driversLicenseClass === "string") {
      return driversLicenseClass || "-";
    }

    if (Array.isArray(driversLicenseClass)) {
      if (driversLicenseClass.length === 0) return "-";

      return (
        driversLicenseClass
          .map((license) => {
            if (typeof license === "string") return license;
            if (license && typeof license === "object") {
              return (
                license.text ||
                license.label ||
                license.name ||
                license.value ||
                ""
              );
            }
            return "";
          })
          .filter(Boolean)
          .join(", ") || "-"
      );
    }

    if (typeof driversLicenseClass === "object") {
      return (
        driversLicenseClass.text ||
        driversLicenseClass.label ||
        driversLicenseClass.name ||
        driversLicenseClass.value ||
        "-"
      );
    }

    return String(driversLicenseClass) || "-";
  }, []);

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

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

  // Format speaker type
  const formatSpeakerType = useCallback((type) => {
    switch (type) {
      case INDIVIDUAL_SPEAKER_TYPE_OF_ID:
        return "Individual";
      case REPRESENTATIVE_SPEAKER_TYPE_OF_ID:
        return "Representative";
      default:
        return "Unknown";
    }
  }, []);

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

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

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

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

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

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

              {speaker?.phone && (
                <div
                  className={`flex items-center ${getThemeClasses("text.secondary")}`}
                >
                  <PhoneIcon className="w-4 h-4 mr-2" />
                  <a
                    href={`tel:${speaker.phone}`}
                    className={getThemeClasses("link")}
                  >
                    {formatPhone(speaker.phone)}
                  </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`}
                >
                  {formatSpeakerType(speaker?.type) || "Not specified"}
                </p>
              </div>

              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  Level
                </label>
                <div className="mt-1">{formatLevel(speaker?.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(speaker?.createdAt)}
                </p>
              </div>
            </div>
          ),
        },
      ],
    }),
    [
      speaker,
      getSpeakerDisplayName,
      formatPhone,
      formatSpeakerType,
      formatLevel,
      getThemeClasses,
    ],
  );

  const contentSections = useMemo(
    () => [
      // Organization Information (for Representative speakers)
      ...(speaker?.type === REPRESENTATIVE_SPEAKER_TYPE_OF_ID
        ? [
            {
              type: "infoCard",
              title: "Organization Information",
              icon: BuildingOfficeIcon,
              primarySections: [
                {
                  component: speaker && (
                    <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`}
                        >
                          {speaker.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`}
                        >
                          {SPEAKER_ORGANIZATION_TYPE_OPTIONS[
                            speaker.representitiveOrganizationType
                          ] || "Not provided"}
                        </p>
                      </div>
                    </div>
                  ),
                },
              ],
              showAvatar: false,
              twoColumn: false,
            },
          ]
        : []),

      {
        type: "infoCard",
        title: "Personal Information",
        icon: UserIcon,
        primarySections: [
          {
            component: speaker && (
              <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`}
                    >
                      {speaker.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`}
                    >
                      {speaker.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`}
                    >
                      {speaker.gender ? (
                        <>
                          {GENDER_OPTIONS[speaker.gender] || "Unknown"}
                          {speaker.gender === 1 &&
                            speaker.genderOther &&
                            ` - ${speaker.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`}
                    >
                      {speaker.description || "Not provided"}
                    </p>
                  </div>
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Availability
                    </label>
                    <div className="mt-1">
                      {formatAvailability(speaker.availability)}
                    </div>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Address Information",
        icon: MapPinIcon,
        primarySections: [
          {
            component: speaker && (
              <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`}
                  >
                    {speaker.fullAddressUrl ? (
                      <a
                        href={speaker.fullAddressUrl}
                        target="_blank"
                        rel="noreferrer"
                        className={`${getThemeClasses("link")} break-words`}
                      >
                        {formatAddress(speaker)}
                      </a>
                    ) : (
                      formatAddress(speaker)
                    )}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Contact Information",
        icon: PhoneIcon,
        primarySections: [
          {
            component: speaker && (
              <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[speaker.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[speaker.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`}
                    >
                      {speaker.isOkToEmail ? (
                        <span
                          className={`inline-flex items-center ${getThemeClasses("text.success")}`}
                        >
                          <CheckCircleIcon className="w-4 h-4 mr-1" />
                          Yes
                        </span>
                      ) : (
                        <span
                          className={`inline-flex items-center ${getThemeClasses("text.error")}`}
                        >
                          <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`}
                    >
                      {speaker.isOkToText ? (
                        <span
                          className={`inline-flex items-center ${getThemeClasses("text.success")}`}
                        >
                          <CheckCircleIcon className="w-4 h-4 mr-1" />
                          Yes
                        </span>
                      ) : (
                        <span
                          className={`inline-flex items-center ${getThemeClasses("text.error")}`}
                        >
                          <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: speaker && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <TagsDisplay
                    values={extractIds(speaker.tags)}
                    onUnauthorized={onUnauthorized}
                  />
                  <SkillSetsDisplay
                    values={extractIds(speaker.skillSets)}
                    onUnauthorized={onUnauthorized}
                  />
                  <CertificationDisplay
                    values={extractIds(speaker.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`}
                    >
                      {speaker.hourlySalaryDesired
                        ? `$${speaker.hourlySalaryDesired}/hr`
                        : "Not provided"}
                    </p>
                  </div>
                </div>
                <div className="space-y-4">
                  <InsuranceRequirementsDisplay
                    values={extractIds(speaker.insuranceRequirements)}
                    onUnauthorized={onUnauthorized}
                  />
                  {speaker.serviceFeeId && (
                    <ServiceFeeDisplay
                      value={speaker.serviceFeeId}
                      onUnauthorized={onUnauthorized}
                      showAmount={true}
                    />
                  )}
                  <VehicleTypesDisplay
                    values={extractIds(speaker.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(speaker.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`}
                    >
                      {speaker.preferredLanguage || "English"}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Insurance & Compliance",
        icon: CheckCircleIcon,
        primarySections: [
          {
            component: speaker && (
              <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(
                        speaker.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(speaker.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`}
                    >
                      {speaker.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(speaker.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(speaker.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`}
                    >
                      {speaker.taxId || "Not provided"}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Emergency Contact",
        icon: ExclamationTriangleIcon,
        primarySections: [
          {
            component: speaker && (
              <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`}
                  >
                    {speaker.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`}
                  >
                    {speaker.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(speaker.emergencyContactTelephone) ||
                      "Not provided"}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "Internal Metrics",
        icon: ChartPieIcon,
        primarySections: [
          {
            component: speaker && (
              <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(
                      speaker.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(speaker.joinDate) || "Not provided"}
                  </p>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },

      {
        type: "infoCard",
        title: "System Information",
        icon: ComputerDesktopIcon,
        primarySections: [
          {
            component: speaker && (
              <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("bg.secondary")} px-2 py-1 rounded break-all`}
                      >
                        {speaker.publicId || speaker.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(speaker.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`}
                    >
                      {speaker.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`}
                    >
                      {speaker.createdFromIpAddress ? (
                        <span className="font-mono text-xs sm:text-sm break-all">
                          {speaker.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 ${
                          speaker.status === 1
                            ? getThemeClasses("badge.success")
                            : getThemeClasses("badge.secondary")
                        }`}
                      >
                        {speaker.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(speaker.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`}
                    >
                      {speaker.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`}
                    >
                      {speaker.modifiedFromIpAddress ? (
                        <span className="font-mono text-xs sm:text-sm break-all">
                          {speaker.modifiedFromIpAddress}
                        </span>
                      ) : (
                        "Not available"
                      )}
                    </p>
                  </div>
                </div>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ],
    [
      speaker,
      extractIds,
      onUnauthorized,
      formatAvailability,
      formatPhone,
      formatAddress,
      formatDriversLicenseClasses,
      formatMultiSelect,
      getThemeClasses,
    ],
  );

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

  return (
    <DetailFullView
      entityData={speaker}
      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 AdminSpeakerFullDetailPage;
