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

import React, { useState, useEffect, useCallback } from "react";
import { useNavigate, useParams } from "react-router";
import {
  useEventOrderManager,
  useAuthManager,
} from "../../../../services/Services";
import { DetailFullView, Badge, useUIXTheme } from "../../../../components/UIX";
import {
  TicketIcon,
  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,
  ClipboardDocumentListIcon,
  ArrowRightIcon,
} from "@heroicons/react/24/outline";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";
import {
  EVENT_ORDER_STATUS_ARCHIVED,
  getEventOrderStatusLabel,
  getEventOrderStatusVariant,
  getEventOrderSectorLabel,
} from "../../../../constants/EventOrder";
import {
  TASK_ITEM_CLOSE_REASON,
  TASK_NO_SURVEY_REASON,
  TASK_ITEM_TYPE,
  TASK_ITEM_STATUS,
} from "../../../../constants/Task";

function AdminEventOrderFullPage() {
  const { eventOrderID } = useParams();
  const navigate = useNavigate();
  const eventOrderManager = useEventOrderManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

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

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

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

  const handleEditOrder = useCallback(() => {
    navigate(`/admin/event-order/${eventOrderID}/edit`);
  }, [navigate, eventOrderID]);

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

  // Helper function to get task route based on task type
  const getTaskRoute = useCallback((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.CREATE_EVENT_CONTRACT]: `/admin/task/${taskId}/create-event-contract`,
      [TASK_ITEM_TYPE.ASSIGN_FACILITATOR]: `/admin/task/${taskId}/assign-facilitator`,
      [TASK_ITEM_TYPE.ASSIGN_SPEAKER]: `/admin/task/${taskId}/assign-speaker`,
      [TASK_ITEM_TYPE.REVIEW_EVENT_CONTRACT]: `/admin/task/${taskId}/review-event-contract`,
      [TASK_ITEM_TYPE.PAY_EVENT_CONTRACT]: `/admin/task/${taskId}/pay-event-contract`,
      [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]: `/admin/task/${taskId}/collect-payment`,
      [TASK_ITEM_TYPE.SURVEY_EVENT_ORDER]: `/admin/task/${taskId}/survey-event-order`,
      [TASK_ITEM_TYPE.SEND_CERTIFICATE]: `/admin/task/${taskId}/send-certificate`,
    };

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

  // Helper function to get task type label
  const getTaskTypeLabel = useCallback((taskType) => {
    const labelMap = {
      [TASK_ITEM_TYPE.CLOSE_EVENT]: "Close Event",
      [TASK_ITEM_TYPE.CREATE_EVENT_ORDER]: "Create Event Order",
      [TASK_ITEM_TYPE.CREATE_EVENT_CONTRACT]: "Create Event Contract",
      [TASK_ITEM_TYPE.ASSIGN_FACILITATOR]: "Assign Facilitator",
      [TASK_ITEM_TYPE.ASSIGN_SPEAKER]: "Assign Speaker",
      [TASK_ITEM_TYPE.REVIEW_EVENT_CONTRACT]: "Review Event Contract",
      [TASK_ITEM_TYPE.PAY_EVENT_CONTRACT]: "Pay Event Contract",
      [TASK_ITEM_TYPE.CLOSE_EVENT_ORDER]: "Close Event Order",
      [TASK_ITEM_TYPE.REVIEW_EVENT_ORDER]: "Review Event Order",
      [TASK_ITEM_TYPE.COLLECT_PAYMENT]: "Collect Payment",
      [TASK_ITEM_TYPE.SURVEY_EVENT_ORDER]: "Survey Event Order",
      [TASK_ITEM_TYPE.SEND_CERTIFICATE]: "Send Certificate",
    };

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

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

    const fetchEventOrderDetail = async () => {
      if (!eventOrderID) {
        setErrors({ general: "Event Order ID is required" });
        setFetching(false);
        return;
      }

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

        const response = await eventOrderManager.getEventOrderDetail(
          eventOrderID,
          onUnauthorized,
        );
        setEventOrder(response);
      } catch (error) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch event order detail:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
      }
    };

    fetchEventOrderDetail();
  }, [eventOrderID, eventOrderManager, authManager]);

  // Helper function to get event order display name
  const getEventOrderDisplayName = (eventOrder) => {
    if (!eventOrder) return "Loading...";
    return `Order #${eventOrder.publicId || eventOrder.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 "Not specified";
    }
  };

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

  // Helper function to format closing reason
  const formatClosingReason = (closingReason) => {
    switch (closingReason) {
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_OTHER:
        return "Other";
      case TASK_ITEM_CLOSE_REASON.SUCCESSFUL:
        return "Successful";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_HOST_ORG_OR_DIVISION:
        return "Cancelled by Host Org/Division";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_FLASHPOINT:
        return "Cancelled by Flashpoint";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_CUSTOMER:
        return "Cancelled by Customer";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_VENUE:
        return "Cancelled by Venue";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_BY_PARTNER:
        return "Cancelled by Partner";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_DUE_TO_EMERGENCY:
        return "Cancelled due to Emergency";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_DUE_TO_VENUE_ISSUE:
        return "Cancelled due to Venue Issue";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_DUE_TO_NON_PAYMENT:
        return "Cancelled due to Non-Payment";
      case TASK_ITEM_CLOSE_REASON.CANCELLED_DUE_TO_SAFETY_ISSUE:
        return "Cancelled due to Safety Issue";
      default:
        return "Not specified";
    }
  };

  // Helper function to format no survey reason
  const formatNoSurveyReason = (reason) => {
    switch (reason) {
      case TASK_NO_SURVEY_REASON.OTHER:
        return "Other reason";
      case TASK_NO_SURVEY_REASON.CLIENT_REFUSED:
        return "Client refused survey";
      case TASK_NO_SURVEY_REASON.TOO_MUCH_TIME_PASSED:
        return "Too much time has passed";
      case TASK_NO_SURVEY_REASON.COULD_NOT_REACH:
        return "Could not reach client";
      default:
        return "Not specified";
    }
  };

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

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

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

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

  const mainInfoCard = {
    title: "Event Order Information",
    icon: TicketIcon,
    primarySections: [
      {
        component: (
          <div className="space-y-4">
            <div>
              <h3 className="text-lg font-semibold ${getThemeClasses('text.primary')}">
                {getEventOrderDisplayName(eventOrder)}
              </h3>
              <p className="text-sm ${getThemeClasses('text.secondary')}">
                Event Order ID: #{eventOrder?.id}
              </p>
            </div>

            {eventOrder?.customerEmail && (
              <div className="flex items-center ${getThemeClasses('text.secondary')}">
                <EnvelopeIcon className="w-4 h-4 mr-2" />
                <a
                  href={`mailto:${eventOrder.customerEmail}`}
                  className="hover:text-blue-600"
                >
                  {eventOrder.customerEmail}
                </a>
              </div>
            )}

            {eventOrder?.customerPhone && (
              <div className="flex items-center ${getThemeClasses('text.secondary')}">
                <PhoneIcon className="w-4 h-4 mr-2" />
                <a
                  href={`tel:${eventOrder.customerPhone}`}
                  className="hover:text-blue-600"
                >
                  {formatPhone(
                    eventOrder.customerPhone,
                    eventOrder.customerPhoneExtension,
                  )}
                </a>
              </div>
            )}
          </div>
        ),
      },
    ],
    secondarySections: [
      {
        component: (
          <div className="space-y-4">
            <div>
              <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                Status
              </label>
              <div className="mt-1">
                <Badge
                  variant={getEventOrderStatusVariant(eventOrder?.status)}
                  size="sm"
                >
                  {getEventOrderStatusLabel(eventOrder?.status)}
                </Badge>
              </div>
            </div>

            <div>
              <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                Event Type
              </label>
              <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                {formatEventType(eventOrder?.eventType)}
              </p>
            </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(eventOrder?.createdAt)}
              </p>
            </div>

            {/* Latest Task */}
            {eventOrder?.latestTaskItemId && (eventOrder?.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE || eventOrder?.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING) && (
              <div>
                <label className="text-sm font-medium text-gray-600 mb-2 block">
                  Latest Task
                </label>
                <button
                  onClick={() => eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE ? navigate(getTaskRoute(eventOrder.latestTaskItemType, eventOrder.latestTaskItemId)) : null}
                  disabled={eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING}
                  className={`inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
                    eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING
                      ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                      : 'bg-blue-600 text-white hover:bg-blue-700'
                  }`}
                >
                  <ClipboardDocumentListIcon className="w-4 h-4" />
                  <span>{getTaskTypeLabel(eventOrder.latestTaskItemType)}</span>
                  {eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.PENDING && (
                    <Badge variant="warning" size="sm">Locked</Badge>
                  )}
                  {eventOrder.latestTaskItemStatus === TASK_ITEM_STATUS.ACTIVE && (
                    <ArrowRightIcon className="w-4 h-4" />
                  )}
                </button>
              </div>
            )}
          </div>
        ),
      },
    ],
  };

  const contentSections = [
    {
      type: "infoCard",
      title: "Customer Information",
      icon: UserIcon,
      primarySections: [
        {
          component: eventOrder && (
            <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')}">
                    Customer Name
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    {eventOrder.customerName ||
                      `${eventOrder.customerFirstName} ${eventOrder.customerLastName}` ||
                      "Not provided"}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Customer ID
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    #{eventOrder.customerPublicId || "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">
                    {formatGender(
                      eventOrder.customerGender,
                      eventOrder.customerGenderOther,
                    )}
                  </p>
                </div>
                {eventOrder.customerBirthdate && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Birth Date
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1 flex items-center">
                      <CakeIcon className="w-4 h-4 mr-1" />
                      {formatDateForDisplay(eventOrder.customerBirthdate)}
                    </p>
                  </div>
                )}
              </div>
              <div className="space-y-4">
                {eventOrder.customerOrganizationName && (
                  <>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Organization Name
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        {eventOrder.customerOrganizationName}
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Organization Type
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        {eventOrder.customerOrganizationType === 2
                          ? "Business"
                          : "Individual"}
                      </p>
                    </div>
                  </>
                )}
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Phone Type
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    {formatPhoneType(eventOrder.customerPhoneType)}
                  </p>
                </div>
                {eventOrder.customerOtherPhone && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Other Phone
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {formatPhone(
                        eventOrder.customerOtherPhone,
                        eventOrder.customerOtherPhoneExtension,
                      )}
                      <span className="text-sm ${getThemeClasses('text.muted')} ml-2">
                        ({formatPhoneType(eventOrder.customerOtherPhoneType)})
                      </span>
                    </p>
                  </div>
                )}
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    ...(eventOrder?.customerFullAddressWithoutPostalCode
      ? [
          {
            type: "infoCard",
            title: "Customer Address",
            icon: MapPinIcon,
            primarySections: [
              {
                component: eventOrder && (
                  <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">
                        {eventOrder.customerFullAddressWithoutPostalCode}
                      </p>
                      {eventOrder.customerFullAddressURL && (
                        <a
                          href={eventOrder.customerFullAddressURL}
                          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: eventOrder && (
            <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">
                    {eventOrder.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">
                    #{eventOrder.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(eventOrder.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(eventOrder.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">
                    {eventOrder.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">
                    {eventOrder.eventDayOfWeek || "Not provided"}
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    AM Facilitator
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    <Badge
                      variant={
                        eventOrder.eventFacilitatorAM ? "success" : "secondary"
                      }
                      size="sm"
                    >
                      {eventOrder.eventFacilitatorAM
                        ? "Required"
                        : "Not Required"}
                    </Badge>
                  </p>
                </div>
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    PM Facilitator
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    <Badge
                      variant={
                        eventOrder.eventFacilitatorPM ? "success" : "secondary"
                      }
                      size="sm"
                    >
                      {eventOrder.eventFacilitatorPM
                        ? "Required"
                        : "Not Required"}
                    </Badge>
                  </p>
                </div>
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

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

    {
      type: "infoCard",
      title: "Academic Information",
      icon: AcademicCapIcon,
      primarySections: [
        {
          component: eventOrder && (
            <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={
                      eventOrder.eventIsSHSM === 1
                        ? "success"
                        : eventOrder.eventIsSHSM === 2
                          ? "error"
                          : "secondary"
                    }
                    size="sm"
                  >
                    {eventOrder.eventIsSHSM === 1
                      ? "Yes"
                      : eventOrder.eventIsSHSM === 2
                        ? "No"
                        : "Unset"}
                  </Badge>
                </p>
              </div>
              {eventOrder.eventPartners && (
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Partners
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    {eventOrder.eventPartners}
                  </p>
                </div>
              )}
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    {
      type: "infoCard",
      title: "Order Information",
      icon: TicketIcon,
      primarySections: [
        {
          component: eventOrder && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                {eventOrder.sector > 0 && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Sector
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {getEventOrderSectorLabel(eventOrder.sector)}
                    </p>
                  </div>
                )}
                {eventOrder.estimatedNumberOfAttendees > 0 && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Estimated Number of Attendees
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1 flex items-center">
                      <UsersIcon className="w-4 h-4 mr-1" />
                      {eventOrder.estimatedNumberOfAttendees}
                    </p>
                  </div>
                )}
                {eventOrder.actualNumberOfAttendees > 0 && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Actual Number of Attendees
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1 flex items-center">
                      <UsersIcon className="w-4 h-4 mr-1" />
                      {eventOrder.actualNumberOfAttendees}
                    </p>
                  </div>
                )}
              </div>
              <div className="space-y-4">
                {eventOrder.varianceOfNumberOfAttendees !== undefined && eventOrder.varianceOfNumberOfAttendees !== 0 && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Variance of Attendees
                    </label>
                    <p className={`text-base mt-1 ${eventOrder.varianceOfNumberOfAttendees >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                      {eventOrder.varianceOfNumberOfAttendees >= 0 ? '+' : ''}{eventOrder.varianceOfNumberOfAttendees}
                    </p>
                  </div>
                )}
                {eventOrder.additionalOrderNotes && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Additional Order Notes
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {eventOrder.additionalOrderNotes}
                    </p>
                  </div>
                )}
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },

    ...(eventOrder?.closingReason > 0 ? [
      {
        type: "infoCard",
        title: "Closure Information",
        icon: NoSymbolIcon,
        primarySections: [
          {
            component: eventOrder && (
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Closing Reason
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    <Badge variant="error" size="sm">
                      {formatClosingReason(eventOrder.closingReason)}
                    </Badge>
                  </p>
                </div>
                {eventOrder.closingReasonOther && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Other Closing Reason
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {eventOrder.closingReasonOther}
                    </p>
                  </div>
                )}
                {eventOrder.additionalClosureNotes && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Additional Closure Notes
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {eventOrder.additionalClosureNotes}
                    </p>
                  </div>
                )}
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ] : []),

    ...(eventOrder?.reviewComment ? [
      {
        type: "infoCard",
        title: "Review",
        icon: CheckCircleIcon,
        primarySections: [
          {
            component: eventOrder && (
              <div>
                <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                  Review Comment
                </label>
                <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                  {eventOrder.reviewComment}
                </p>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ] : []),

    ...(eventOrder?.collectPaymentComment ? [
      {
        type: "infoCard",
        title: "Payment Collection",
        icon: CheckCircleIcon,
        primarySections: [
          {
            component: eventOrder && (
              <div>
                <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                  Payment Comment
                </label>
                <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                  {eventOrder.collectPaymentComment}
                </p>
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ] : []),

    ...(eventOrder?.surveyConducted || eventOrder?.surveyComment ? [
      {
        type: "infoCard",
        title: "Client Survey",
        icon: ChatBubbleLeftRightIcon,
        primarySections: [
          {
            component: eventOrder && (
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Survey Conducted
                  </label>
                  <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                    <Badge variant={eventOrder.surveyConducted ? "success" : "secondary"} size="sm">
                      {eventOrder.surveyConducted ? "Yes" : "No"}
                    </Badge>
                  </p>
                </div>

                {eventOrder.surveyConducted ? (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Facilitators Punctual
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        <Badge variant={eventOrder.facilitatorsPunctual ? "success" : "error"} size="sm">
                          {eventOrder.facilitatorsPunctual ? "Yes" : "No"}
                        </Badge>
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Facilitators Professional
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        <Badge variant={eventOrder.facilitatorsProfessional ? "success" : "error"} size="sm">
                          {eventOrder.facilitatorsProfessional ? "Yes" : "No"}
                        </Badge>
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Students Engaged
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        <Badge variant={eventOrder.studentsEngaged ? "success" : "error"} size="sm">
                          {eventOrder.studentsEngaged ? "Yes" : "No"}
                        </Badge>
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Material Relevant
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        <Badge variant={eventOrder.materialRelevant ? "success" : "error"} size="sm">
                          {eventOrder.materialRelevant ? "Yes" : "No"}
                        </Badge>
                      </p>
                    </div>
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Would Consider Flashpoint Again
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        <Badge variant={eventOrder.wouldConsiderAgain ? "success" : "error"} size="sm">
                          {eventOrder.wouldConsiderAgain ? "Yes" : "No"}
                        </Badge>
                      </p>
                    </div>
                  </div>
                ) : (
                  eventOrder.noSurveyReason > 0 && (
                    <div>
                      <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                        Reason Survey Not Conducted
                      </label>
                      <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                        {formatNoSurveyReason(eventOrder.noSurveyReason)}
                      </p>
                    </div>
                  )
                )}

                {eventOrder.surveyComment && (
                  <div>
                    <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                      Survey Comments
                    </label>
                    <p className="text-base ${getThemeClasses('text.primary')} mt-1">
                      {eventOrder.surveyComment}
                    </p>
                  </div>
                )}
              </div>
            ),
          },
        ],
        showAvatar: false,
        twoColumn: false,
      },
    ] : []),

    ...(eventOrder?.eventListingURL
      ? [
          {
            type: "infoCard",
            title: "External Links",
            icon: GlobeAltIcon,
            primarySections: [
              {
                component: eventOrder && (
                  <div>
                    <a
                      href={eventOrder.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,
          },
        ]
      : []),

    ...((eventOrder?.customerTags && eventOrder.customerTags.length > 0) ||
    (eventOrder?.eventTags && eventOrder.eventTags.length > 0) ||
    (eventOrder?.eventSkillSets && eventOrder.eventSkillSets.length > 0)
      ? [
          {
            type: "infoCard",
            title: "Tags & Skills",
            icon: TagIcon,
            primarySections: [
              {
                component: eventOrder && (
                  <div className="space-y-6">
                    {eventOrder.customerTags &&
                      eventOrder.customerTags.length > 0 && (
                        <div>
                          <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                            Customer Tags
                          </label>
                          <div className="flex flex-wrap gap-2 mt-2">
                            {eventOrder.customerTags
                              .filter((tag) => tag && tag.text)
                              .map((tag, index) => (
                                <Badge
                                  key={index}
                                  variant="secondary"
                                  size="sm"
                                >
                                  {tag.text}
                                </Badge>
                              ))}
                          </div>
                        </div>
                      )}
                    {eventOrder.eventTags &&
                      eventOrder.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">
                            {eventOrder.eventTags
                              .filter((tag) => tag && tag.text)
                              .map((tag, index) => (
                                <Badge
                                  key={index}
                                  variant="secondary"
                                  size="sm"
                                >
                                  {tag.text}
                                </Badge>
                              ))}
                          </div>
                        </div>
                      )}
                    {eventOrder.eventSkillSets &&
                      eventOrder.eventSkillSets.length > 0 && (
                        <div>
                          <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                            Skill Sets
                          </label>
                          <div className="space-y-2 mt-2">
                            {eventOrder.eventSkillSets
                              .filter(
                                (skillSet) => skillSet && skillSet.category,
                              )
                              .map((skillSet, index) => (
                                <div
                                  key={index}
                                  className="${getThemeClasses('card.background')} rounded p-3"
                                >
                                  <div className="font-medium ${getThemeClasses('text.primary')}">
                                    {skillSet.category}
                                  </div>
                                  {skillSet.subCategory && (
                                    <div className="text-sm ${getThemeClasses('text.secondary')}">
                                      {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: eventOrder && (
            <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">
                      {eventOrder.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">
                      {eventOrder.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(eventOrder.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">
                    {eventOrder.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">
                    {eventOrder.createdFromIPAddress ? (
                      <span className="font-mono text-xs sm:text-sm break-all">
                        {eventOrder.createdFromIPAddress}
                      </span>
                    ) : (
                      "Not available"
                    )}
                  </p>
                </div>
              </div>
              <div className="space-y-4">
                <div>
                  <label className="text-sm font-medium ${getThemeClasses('text.secondary')}">
                    Customer 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">
                      {eventOrder.customerId || "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">
                      {eventOrder.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(eventOrder.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">
                    {eventOrder.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">
                    {eventOrder.modifiedFromIPAddress ? (
                      <span className="font-mono text-xs sm:text-sm break-all">
                        {eventOrder.modifiedFromIPAddress}
                      </span>
                    ) : (
                      "Not available"
                    )}
                  </p>
                </div>
              </div>
            </div>
          ),
        },
      ],
      showAvatar: false,
      twoColumn: false,
    },
  ];

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

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