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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  useEventContractManager,
  useAuthManager,
} from "../../../../services/Services";
import { DetailFullView, Badge, useUIXTheme } from "../../../../components/UIX";
import {
  DocumentCheckIcon,
  UserIcon,
  CalendarIcon,
  MapPinIcon,
  ClockIcon,
  EnvelopeIcon,
  PhoneIcon,
  InformationCircleIcon,
  ExclamationTriangleIcon,
  BuildingOfficeIcon,
  CakeIcon,
  TagIcon,
  LinkIcon,
  UsersIcon,
  AcademicCapIcon,
  GlobeAltIcon,
  ComputerDesktopIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  EllipsisHorizontalIcon,
  ArchiveBoxIcon,
  CheckCircleIcon,
  ChevronLeftIcon,
  PencilSquareIcon,
  NoSymbolIcon,
  HomeIcon,
  UserGroupIcon,
  ClipboardDocumentListIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";
import {
  EVENT_CONTRACT_STATUS_ARCHIVED,
  getEventContractStatusLabel,
  getEventContractStatusVariant,
} from "../../../../constants/EventContract";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_TYPE_ONSITE,
  EVENT_TYPE_OFFSITE,
  EVENT_TYPE_VIRTUAL,
} from "../../../../constants/Event";
import {
  TASK_ITEM_TYPE,
  TASK_ITEM_STATUS,
} from "../../../../constants/Task";

/**
 * Helper function to get task route based on task type
 */
const getTaskRoute = (taskType, taskId) => {
  if (!taskId) return null;

  const routeMap = {
    [TASK_ITEM_TYPE.CLOSE_EVENT]: `/admin/task/${taskId}/close-event`,
    [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: `/admin/task/${taskId}/create-event-order`,
    [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: `/admin/task/${taskId}/close-event-order`,
    [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: `/admin/task/${taskId}/review-event-order`,
    [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]: `/admin/task/${taskId}/collect-payment-for-event-order`,
    [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]: `/admin/task/${taskId}/client-survey-for-event-order`,
    [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: `/admin/task/${taskId}/create-event-contract`,
    [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]: `/admin/task/${taskId}`,
    [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: `/admin/task/${taskId}/close-event-contract`,
    [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: `/admin/task/${taskId}/review-event-contract`,
    [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: `/admin/task/${taskId}/pay-facilitator-or-speaker-for-event-contract`,
    [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: `/admin/task/${taskId}/survey-facilitator-or-speaker-for-event-contract`,
  };

  return routeMap[taskType] || `/admin/task/${taskId}`;
};

/**
 * Helper function to get task type label
 */
const getTaskTypeLabel = (taskType) => {
  const labelMap = {
    [TASK_ITEM_TYPE.CLOSE_EVENT]: "Close Event",
    [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "Create Event Order",
    [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "Close Event Order",
    [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "Review Event Order",
    [TASK_ITEM_TYPE.COLLECT_PAYMENT_FOR_EVENT_ORDER]: "Collect Payment for Event Order",
    [TASK_ITEM_TYPE.SURVEY_CLIENT_FOR_EVENT_ORDER]: "Survey Client for Event Order",
    [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "Create Event Contract",
    [TASK_ITEM_TYPE.ASSIGN_FACILITATOR_OR_SPEAKER_TO_EVENT]: "Assign Facilitator/Speaker",
    [TASK_ITEM_TYPE.CLOSE_EVENT_CONTRACT]: "Close Event Contract",
    [TASK_ITEM_TYPE.EVENT_CONTRACT_REVIEW]: "Review Event Contract",
    [TASK_ITEM_TYPE.PAY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "Pay Facilitator/Speaker",
    [TASK_ITEM_TYPE.SURVEY_FACILITATOR_OR_SPEAKER_FOR_EVENT_CONTRACT]: "Survey Facilitator/Speaker",
  };

  return labelMap[taskType] || "View Task";
};

// Helper function to get event type label
const getEventTypeLabel = (eventType) => {
  const typeNum =
    typeof eventType === "string" ? parseInt(eventType, 10) : eventType;
  switch (typeNum) {
    case EVENT_TYPE_CONFERENCE:
      return "Conference";
    case EVENT_TYPE_ONSITE:
      return "Onsite";
    case EVENT_TYPE_OFFSITE:
      return "Offsite";
    case EVENT_TYPE_VIRTUAL:
      return "Virtual";
    default:
      return "";
  }
};

function AdminEventContractFullPage() {
  const { eventContractID } = useParams();
  const navigate = useNavigate();
  const eventContractManager = useEventContractManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

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

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

  // Stable navigation callbacks
  const handleBackToContracts = useCallback(() => {
    navigate("/admin/event-contracts");
  }, [navigate]);

  const handleEditContract = useCallback(() => {
    navigate(`/admin/event-contract/${eventContractID}/edit`);
  }, [navigate, eventContractID]);

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

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

    const fetchEventContractDetail = async () => {
      if (!eventContractID) {
        setErrors({ general: "Event Contract ID is required" });
        setFetching(false);
        return;
      }

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

        const response = await eventContractManager.getEventContractDetail(
          eventContractID,
          onUnauthorized,
        );
        setEventContract(response);
      } catch (error) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch event contract detail:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
      }
    };

    fetchEventContractDetail();
  }, [eventContractID, eventContractManager, authManager]);

  // Helper function to get event contract display name
  const getEventContractDisplayName = (eventContract) => {
    if (!eventContract) return "Unknown Contract";
    if (eventContract.name) return eventContract.name;
    return `Contract #${eventContract.publicId || eventContract.id}`;
  };

  // Helper function to format phone numbers
  const formatPhone = (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;
  };

  // Helper function to format event type
  const formatEventType = (eventType) => {
    switch (eventType) {
      case 1:
        return "Field Trip";
      case 2:
        return "In-School";
      case 3:
        return "Conference";
      case 4:
        return "Virtual";
      default:
        return "Unknown";
    }
  };

  // Helper function to format gender
  const formatGender = (gender, genderOther) => {
    switch (gender) {
      case 1:
        return "Male";
      case 2:
        return "Female";
      case 3:
        return genderOther ? `Other (${genderOther})` : "Other";
      default:
        return "—";
    }
  };

  // Helper function to format phone type
  const formatPhoneType = (phoneType) => {
    switch (phoneType) {
      case 1:
        return "Mobile";
      case 2:
        return "Work";
      case 3:
        return "Home";
      default:
        return "Other";
    }
  };

  // Configure DetailFullView props
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Event Contracts",
      to: "/admin/event-contracts",
      icon: DocumentCheckIcon,
    },
    {
      label: "Full Details",
      icon: InformationCircleIcon,
      isActive: true,
    },
  ];

  const headerConfig = {
    title: "Event Contract - Full Details",
    icon: DocumentCheckIcon,
    loadingText: "Loading event contract details...",
    notFoundTitle: "Event Contract Not Found",
    notFoundMessage:
      "The event contract you're looking for doesn't exist or you don't have permission to view it.",
    notFoundAction: {
      label: "Back to Event Contracts",
      icon: ChevronLeftIcon,
      onClick: handleBackToContracts,
    },
  };

  const actionButtons = [
    {
      variant: "outline",
      onClick: handleBackToContracts,
      icon: ChevronLeftIcon,
      label: "Back",
    },
    {
      variant: "secondary",
      onClick: handleEditContract,
      icon: PencilSquareIcon,
      label: "Edit",
    },
  ];

  const tabs = [
    {
      label: "Summary",
      to: `/admin/event-contract/${eventContractID}`,
    },
    {
      label: "Full Details",
      isActive: true,
    },
    {
      label: "Comments",
      to: `/admin/event-contract/${eventContractID}/comments`,
    },
    {
      label: "Attachments",
      to: `/admin/event-contract/${eventContractID}/attachments`,
    },
    {
      label: "More",
      to: `/admin/event-contract/${eventContractID}/more`,
      icon: EllipsisHorizontalIcon,
    },
  ];

  const contentSections = [
    // Summary Card
    {
      type: "infoCard",
      title: "Summary",
      icon: InformationCircleIcon,
      primarySections: [
        {
          component: eventContract && (
            <div>
              <h3
                className={`text-base sm:text-lg md:text-xl lg:text-2xl font-semibold ${getThemeClasses("text.primary")}`}
              >
                <span className="break-words">
                  {eventContract?.event?.name ||
                    eventContract?.eventName ||
                    "Event Contract"}
                </span>
              </h3>

              {/* Event Type */}
              {eventContract?.eventType > 0 && (
                <div className="mt-2">
                  <span
                    className={`text-sm font-bold ${getThemeClasses("text.secondary")}`}
                  >
                    {getEventTypeLabel(eventContract.eventType)}
                  </span>
                </div>
              )}

              {/* Event Category */}
              {eventContract?.eventCategory?.name && (
                <div className="mt-2">
                  <span
                    className={`text-sm font-bold ${getThemeClasses("text.primary")}`}
                  >
                    {eventContract.eventCategory.name}
                  </span>
                </div>
              )}

              {/* Skills, Certifications, and Specializations Pills */}
              {(eventContract?.certifications?.length > 0 ||
                eventContract?.specializations?.length > 0 ||
                eventContract?.eventSkillSets?.length > 0 ||
                eventContract?.facilitatorSkillSets?.length > 0 ||
                eventContract?.speakerSkillSets?.length > 0) && (
                <div className="mt-3 flex flex-wrap gap-2">
                  {eventContract?.certifications?.map((cert) => (
                    <Badge key={cert.id} variant="secondary" size="sm">
                      {cert.name}
                    </Badge>
                  ))}
                  {eventContract?.specializations?.map((spec) => (
                    <Badge key={spec.id} variant="info" size="sm">
                      {spec.name}
                    </Badge>
                  ))}
                  {eventContract?.eventSkillSets?.map((skill) => (
                    <Badge
                      key={`event-${skill.id}`}
                      variant="success"
                      size="sm"
                    >
                      {skill.subCategory ||
                        skill.category ||
                        skill.description ||
                        "Skill Set"}
                    </Badge>
                  ))}
                  {eventContract?.facilitatorSkillSets?.map((skill) => (
                    <Badge
                      key={`facilitator-${skill.id}`}
                      variant="success"
                      size="sm"
                    >
                      {skill.subCategory ||
                        skill.category ||
                        skill.description ||
                        "Skill Set"}
                    </Badge>
                  ))}
                  {eventContract?.speakerSkillSets?.map((skill) => (
                    <Badge
                      key={`speaker-${skill.id}`}
                      variant="success"
                      size="sm"
                    >
                      {skill.subCategory ||
                        skill.category ||
                        skill.description ||
                        "Skill Set"}
                    </Badge>
                  ))}
                </div>
              )}

              <div
                className={`mt-2 text-sm lg:text-base ${getThemeClasses("text.secondary")} flex flex-wrap gap-2`}
              >
                <Badge
                  variant={getEventContractStatusVariant(eventContract.status)}
                  size="sm"
                >
                  {getEventContractStatusLabel(eventContract.status)}
                </Badge>
              </div>

              {/* Date, Time, and Attendees Information */}
              <div className="mt-4 space-y-2">
                {/* Date and Time Range */}
                {(eventContract?.eventStartDateTime ||
                  eventContract?.eventEndDateTime) && (
                  <div
                    className={`flex items-center text-sm ${getThemeClasses("text.secondary")}`}
                  >
                    <CalendarIcon
                      className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                    />
                    <span>
                      {eventContract.eventStartDateTime &&
                      eventContract.eventEndDateTime
                        ? `${eventContract.eventStartDateTime} - ${eventContract.eventEndDateTime}`
                        : eventContract.eventStartDateTime ||
                          eventContract.eventEndDateTime}
                    </span>
                  </div>
                )}

                {/* Attendees */}
                {eventContract?.eventAttendeeCapacity && (
                  <div
                    className={`flex items-center text-sm ${getThemeClasses("text.secondary")}`}
                  >
                    <UserGroupIcon
                      className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                    />
                    <span>{eventContract.eventAttendeeCapacity} attendees</span>
                  </div>
                )}

                {/* Facilitator */}
                <div
                  className={`flex items-center text-sm ${getThemeClasses("text.secondary")}`}
                >
                  <UserIcon
                    className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                  />
                  <span className="font-medium">Facilitator:</span>
                  <span className="ml-2">
                    {eventContract?.facilitator
                      ? eventContract.facilitator.name ||
                        `${eventContract.facilitator.firstName} ${eventContract.facilitator.lastName}`.trim()
                      : "—"}
                  </span>
                </div>

                {/* Hours */}
                <div
                  className={`flex items-center text-sm ${getThemeClasses("text.secondary")}`}
                >
                  <ClockIcon
                    className={`w-4 h-4 mr-2 ${getThemeClasses("text.muted")}`}
                  />
                  <span className="font-medium">Hours:</span>
                  <span className="ml-2">
                    {eventContract?.estimatedContractHours || "—"}
                  </span>
                </div>

                {/* Latest Task */}
                {eventContract?.latestTaskItemId && (eventContract?.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE || eventContract?.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING) && (
                  <div className="mt-4">
                    <p className={`text-sm font-medium ${getThemeClasses("text.secondary")} mb-2`}>
                      Latest Task
                    </p>
                    <button
                      onClick={() => eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE ? navigate(getTaskRoute(eventContract.latestTaskItemType, eventContract.latestTaskItemId)) : null}
                      disabled={eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING}
                      className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                        eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING
                          ? `${getThemeClasses("bg-muted")} ${getThemeClasses("text-muted")} cursor-not-allowed`
                          : `${getThemeClasses("bg-primary")} ${getThemeClasses("text-white")} hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 ${getThemeClasses("focus-ring")}`
                      }`}
                    >
                      <ClipboardDocumentListIcon className="w-4 h-4" />
                      <span>{getTaskTypeLabel(eventContract.latestTaskItemType)}</span>
                      {eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING && (
                        <Badge variant="warning" size="sm">Locked</Badge>
                      )}
                      {eventContract.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE && (
                        <ArrowRightIcon className="w-4 h-4" />
                      )}
                    </button>
                  </div>
                )}
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },
    {
      type: "infoCard",
      title: "Facilitator Information",
      icon: UserIcon,
      primarySections: [
        {
          component: eventContract && (
            <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")}`}
                  >
                    Facilitator Name
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.facilitatorName ||
                      (eventContract.facilitatorFirstName &&
                      eventContract.facilitatorLastName
                        ? `${eventContract.facilitatorFirstName} ${eventContract.facilitatorLastName}`.trim()
                        : "—")}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Gender
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatGender(
                      eventContract.facilitatorGender,
                      eventContract.facilitatorGenderOther,
                    )}
                  </p>
                </div>
              </div>
              <div className="space-y-4">
                {eventContract.facilitatorOrganizationName && (
                  <>
                    <div>
                      <label
                        className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                      >
                        Organization Name
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                      >
                        {eventContract.facilitatorOrganizationName}
                      </p>
                    </div>
                    <div>
                      <label
                        className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                      >
                        Organization Type
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                      >
                        {eventContract.facilitatorOrganizationType === 2
                          ? "Business"
                          : "Individual"}
                      </p>
                    </div>
                  </>
                )}
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Phone
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.facilitatorPhone
                      ? formatPhone(
                          eventContract.facilitatorPhone,
                          eventContract.facilitatorPhoneExtension,
                        )
                      : "—"}
                  </p>
                </div>
                {eventContract.facilitatorOtherPhone && (
                  <div>
                    <label
                      className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                    >
                      Other Phone
                    </label>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                    >
                      {formatPhone(
                        eventContract.facilitatorOtherPhone,
                        eventContract.facilitatorOtherPhoneExtension,
                      )}
                      <span
                        className={`text-sm ${getThemeClasses("text.muted")} ml-2`}
                      >
                        (
                        {formatPhoneType(
                          eventContract.facilitatorOtherPhoneType,
                        )}
                        )
                      </span>
                    </p>
                  </div>
                )}
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    ...(eventContract?.facilitatorFullAddressWithoutPostalCode
      ? [
          {
            type: "infoCard",
            title: "Facilitator Address",
            icon: MapPinIcon,
            primarySections: [
              {
                component: eventContract && (
                  <div className="space-y-3">
                    <div>
                      <label
                        className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                      >
                        Address
                      </label>
                      <p
                        className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                      >
                        {eventContract.facilitatorFullAddressWithoutPostalCode}
                      </p>
                      {eventContract.facilitatorFullAddressURL && (
                        <a
                          href={eventContract.facilitatorFullAddressURL}
                          target="_blank"
                          rel="noopener noreferrer"
                          className={`${getThemeClasses("link")} text-sm flex items-center mt-1`}
                        >
                          <LinkIcon className="w-4 h-4 mr-1" />
                          View on Map
                        </a>
                      )}
                    </div>
                  </div>
                ),
              },
            ],
            showAvatar: false,
            twoColumn: false,
          },
        ]
      : []),

    {
      type: "infoCard",
      title: "Event Details",
      icon: CalendarIcon,
      primarySections: [
        {
          component: eventContract && (
            <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")}`}
                  >
                    Event Name
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.eventName || "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Event ID
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    #{eventContract.eventPublicId || "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Start Date & Time
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatDateForDisplay(eventContract.eventStartDateTime) ||
                      "Not provided"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    End Date & Time
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {formatDateForDisplay(eventContract.eventEndDateTime) ||
                      "Not provided"}
                  </p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Expected Attendees
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.eventAttendeeCapacity || "Not specified"}
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Day of Week
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.eventDayOfWeek || "Not provided"}
                  </p>
                </div>
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    ...(eventContract?.eventDescription
      ? [
          {
            type: "infoCard",
            title: "Event Description",
            icon: InformationCircleIcon,
            primarySections: [
              {
                component: eventContract && (
                  <div>
                    <p
                      className={`text-base ${getThemeClasses("text.primary")}`}
                    >
                      {eventContract.eventDescription}
                    </p>
                  </div>
                ),
              },
            ],
            showAvatar: false,
            twoColumn: false,
          },
        ]
      : []),

    {
      type: "infoCard",
      title: "Academic Information",
      icon: AcademicCapIcon,
      primarySections: [
        {
          component: eventContract && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label
                  className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                >
                  SHSM Related
                </label>
                <p
                  className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                >
                  <Badge
                    variant={
                      eventContract.eventIsShsm === 1
                        ? "success"
                        : eventContract.eventIsShsm === 2
                          ? "error"
                          : "secondary"
                    }
                    size="sm"
                  >
                    {eventContract.eventIsShsm === 1
                      ? "Yes"
                      : eventContract.eventIsShsm === 2
                        ? "No"
                        : "Unset"}
                  </Badge>
                </p>
              </div>
              {eventContract.eventPartners && (
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Partners
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    {eventContract.eventPartners}
                  </p>
                </div>
              )}
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    ...(eventContract?.eventListingURL
      ? [
          {
            type: "infoCard",
            title: "External Links",
            icon: GlobeAltIcon,
            primarySections: [
              {
                component: eventContract && (
                  <div>
                    <a
                      href={eventContract.eventListingURL}
                      target="_blank"
                      rel="noopener noreferrer"
                      className={`${getThemeClasses("link")} flex items-center`}
                    >
                      <LinkIcon className="w-4 h-4 mr-1" />
                      View Event Listing
                    </a>
                  </div>
                ),
              },
            ],
            showAvatar: false,
            twoColumn: false,
          },
        ]
      : []),

    ...((eventContract?.facilitatorTags &&
      eventContract.facilitatorTags.length > 0) ||
    (eventContract?.eventTags && eventContract.eventTags.length > 0) ||
    (eventContract?.eventSkillSets && eventContract.eventSkillSets.length > 0)
      ? [
          {
            type: "infoCard",
            title: "Tags & Skills",
            icon: TagIcon,
            primarySections: [
              {
                component: eventContract && (
                  <div className="space-y-6">
                    {eventContract.facilitatorTags &&
                      eventContract.facilitatorTags.length > 0 && (
                        <div>
                          <label
                            className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                          >
                            Facilitator Tags
                          </label>
                          <div className="flex flex-wrap gap-2 mt-2">
                            {eventContract.facilitatorTags
                              .filter((tag) => tag && tag.text)
                              .map((tag, index) => (
                                <Badge
                                  key={index}
                                  variant="secondary"
                                  size="sm"
                                >
                                  {tag.text}
                                </Badge>
                              ))}
                          </div>
                        </div>
                      )}
                    {eventContract.eventTags &&
                      eventContract.eventTags.length > 0 && (
                        <div>
                          <label
                            className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                          >
                            Event Tags
                          </label>
                          <div className="flex flex-wrap gap-2 mt-2">
                            {eventContract.eventTags
                              .filter((tag) => tag && tag.text)
                              .map((tag, index) => (
                                <Badge
                                  key={index}
                                  variant="secondary"
                                  size="sm"
                                >
                                  {tag.text}
                                </Badge>
                              ))}
                          </div>
                        </div>
                      )}
                    {eventContract.eventSkillSets &&
                      eventContract.eventSkillSets.length > 0 && (
                        <div>
                          <label
                            className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                          >
                            Skill Sets
                          </label>
                          <div className="space-y-2 mt-2">
                            {eventContract.eventSkillSets
                              .filter(
                                (skillSet) => skillSet && skillSet.subCategory,
                              )
                              .map((skillSet, index) => (
                                <div
                                  key={index}
                                  className={`${getThemeClasses("card.background")} rounded p-3`}
                                >
                                  <div
                                    className={`font-medium ${getThemeClasses("text.primary")}`}
                                  >
                                    {skillSet.subCategory}
                                  </div>
                                  {skillSet.description && (
                                    <div
                                      className={`text-sm ${getThemeClasses("text.muted")} mt-1`}
                                    >
                                      {skillSet.description}
                                    </div>
                                  )}
                                </div>
                              ))}
                          </div>
                        </div>
                      )}
                  </div>
                ),
              },
            ],
            showAvatar: false,
            twoColumn: false,
          },
        ]
      : []),

    {
      type: "infoCard",
      title: "System Information",
      icon: ComputerDesktopIcon,
      primarySections: [
        {
          component: eventContract && (
            <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")}`}
                  >
                    Database ID
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    <span
                      className={`font-mono text-xs sm:text-sm ${getThemeClasses("code.background")} px-2 py-1 rounded break-all`}
                    >
                      {eventContract.id || "Not available"}
                    </span>
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Public ID
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    <span
                      className={`font-mono text-xs sm:text-sm ${getThemeClasses("code.background")} px-2 py-1 rounded break-all`}
                    >
                      {eventContract.publicId || "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(eventContract.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`}
                  >
                    {eventContract.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`}
                  >
                    {eventContract.createdFromIPAddress ? (
                      <span className="font-mono text-xs sm:text-sm break-all">
                        {eventContract.createdFromIPAddress}
                      </span>
                    ) : (
                      "Not available"
                    )}
                  </p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Facilitator ID
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    <span
                      className={`font-mono text-xs sm:text-sm ${getThemeClasses("code.background")} px-2 py-1 rounded break-all`}
                    >
                      {eventContract.facilitatorId || "Not available"}
                    </span>
                  </p>
                </div>
                <div>
                  <label
                    className={`text-sm font-medium ${getThemeClasses("text.secondary")}`}
                  >
                    Event ID
                  </label>
                  <p
                    className={`text-base ${getThemeClasses("text.primary")} mt-1`}
                  >
                    <span
                      className={`font-mono text-xs sm:text-sm ${getThemeClasses("code.background")} px-2 py-1 rounded break-all`}
                    >
                      {eventContract.eventId || "Not available"}
                    </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(eventContract.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`}
                  >
                    {eventContract.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`}
                  >
                    {eventContract.modifiedFromIPAddress ? (
                      <span className="font-mono text-xs sm:text-sm break-all">
                        {eventContract.modifiedFromIPAddress}
                      </span>
                    ) : (
                      "Not available"
                    )}
                  </p>
                </div>
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },
  ];

  const alerts = {
    archived: {
      message: "This event contract is archived",
      icon: ArchiveBoxIcon,
    },
    banned: {
      message: "This event contract has issues",
      icon: NoSymbolIcon,
    },
  };

  return (
    <DetailFullView
      entityData={eventContract}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      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 AdminEventContractFullPage;
