// File Path: monorepo/web/frontend/src/pages/Admin/Customer/Detail/EventOrder/List/Page.jsx

import React, {
  useState,
  useEffect,
  useCallback,
  useMemo,
  useRef,
} from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  WrenchScrewdriverIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  ChatBubbleLeftRightIcon,
  PaperClipIcon,
  ChevronRightIcon,
  ExclamationTriangleIcon,
  XCircleIcon,
  HomeIcon,
  BuildingOfficeIcon,
  QuestionMarkCircleIcon,
  ArrowTopRightOnSquareIcon,
  CurrencyDollarIcon,
  ArrowRightIcon,
  PlusIcon,
  UserIcon,
  BellAlertIcon,
} from "@heroicons/react/24/outline";
import {
  useEventOrderManager,
  useCustomerManager,
  useAuthManager,
} from "../../../../../../services/Services";
import { useUIXTheme } from "../../../../../../components/UIX";
import { DateTime } from "luxon";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import { CUSTOMER_STATUS } from "../../../../../../constants/Customer";
import { SETTINGS_PAGINATION } from "../../../../../../constants/Settings";
import {
  EVENT_ORDER_STATUS_ACTIVE,
  EVENT_ORDER_STATUS_ARCHIVED,
  getEventOrderStatusLabel,
  getEventOrderStatusVariant,
} from "../../../../../../constants/EventOrder";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_TYPE_ONSITE,
  EVENT_TYPE_OFFSITE,
  EVENT_TYPE_VIRTUAL,
} from "../../../../../../constants/Event";

// Event type mappings (from Event entity)
const EVENT_TYPE_OPTIONS = {
  0: { label: "-", icon: null },
  [EVENT_TYPE_CONFERENCE]: { label: "Conference", icon: BuildingOfficeIcon },
  [EVENT_TYPE_ONSITE]: { label: "Onsite", icon: UserGroupIcon },
  [EVENT_TYPE_OFFSITE]: { label: "Offsite", icon: ChartBarIcon },
  [EVENT_TYPE_VIRTUAL]: { label: "Virtual", icon: ChartBarIcon },
};

function AdminCustomerDetailEventOrderListPage() {
  const { cid } = useParams();
  const navigate = useNavigate();
  const eventOrderManager = useEventOrderManager();
  const customerManager = useCustomerManager();
  const authManager = useAuthManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [isRefreshing, setRefreshing] = useState(false);
  const [customer, setCustomer] = useState({});
  const [eventOrderList, setEventOrderList] = useState([]);
  const [totalCount, setTotalCount] = useState(0);

  // Pagination state using cursor-based approach
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");
  const [hasNextPage, setHasNextPage] = useState(false);
  const [cursorHistory, setCursorHistory] = useState([]);
  const [pageSize, setPageSize] = useState(
    SETTINGS_PAGINATION.DEFAULT_PAGE_SIZE,
  );

  // Filter and sort state
  const [sortByValue, setSortByValue] = useState("created_at,DESC");
  const [status, setStatus] = useState(0);
  const [createdAtGTE] = useState(null);
  const [lastFetchTime, setLastFetchTime] = useState(null);

  // Use refs to track the latest filter values to avoid stale closures
  const filtersRef = useRef({
    sortByValue,
    status,
    pageSize,
    createdAtGTE,
  });

  // Update refs when filters change
  useEffect(() => {
    filtersRef.current = {
      sortByValue,
      status,
      pageSize,
      createdAtGTE,
    };
  }, [sortByValue, status, pageSize, createdAtGTE]);

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

  // Fetch customer details
  const fetchCustomerDetail = useCallback(async () => {
    try {
      const data = await customerManager.getCustomerDetail(cid, onUnauthorized);
      setCustomer(data);
    } catch (error) {
      if (import.meta.env.DEV) {
        console.error("Failed to fetch customer detail:", error);
      }
      setErrors(error);
    }
  }, [cid, customerManager, onUnauthorized]);

  // Fetch eventOrder list with force refresh option - now uses refs for filter values
  const fetchEventOrderList = useCallback(
    async (cursor = "", isNavigatingBack = false) => {
      // Get the latest filter values from refs
      const currentFilters = filtersRef.current;

      setFetching(true);
      setErrors({});

      // Always clear the cache when fetching with new filters
      if (!isNavigatingBack) {
        eventOrderManager.clearEventOrdersCache();
      }

      try {
        // Build filters map (matching old implementation)
        const filtersMap = new Map();

        // Add cursor if provided
        if (cursor) {
          filtersMap.set("cursor", cursor);
        }

        // Add page size
        filtersMap.set("page_size", currentFilters.pageSize.toString());

        // IMPORTANT: Always include customer_id filter
        filtersMap.set("customerId", cid);

        // Handle sorting
        const sortArray = currentFilters.sortByValue.split(",");
        filtersMap.set("sortField", sortArray[0]);
        filtersMap.set("sortEventOrder", sortArray[1]);

        // Add status filter if not "All"
        if (currentFilters.status !== 0) {
          filtersMap.set("status", currentFilters.status.toString());
        }

        // Add date filter if set
        if (
          currentFilters.createdAtGTE !== undefined &&
          currentFilters.createdAtGTE !== null &&
          currentFilters.createdAtGTE !== ""
        ) {
          const dateStr = currentFilters.createdAtGTE.getTime();
          filtersMap.set("createdAtGte", dateStr);
        }

        // Use the legacy method for compatibility with forceRefresh
        const data = await eventOrderManager.getEventOrdersWithFiltersMap(
          filtersMap,
          onUnauthorized,
          true, // Always force refresh
        );

        setEventOrderList(data);
        setTotalCount(data.count || 0);

        // Handle pagination response
        if (
          data.nextCursor !== undefined &&
          data.nextCursor !== null &&
          data.nextCursor !== ""
        ) {
          setNextCursor(data.nextCursor);
          setHasNextPage(true);
        } else {
          setNextCursor("");
          setHasNextPage(false);
        }

        // Alternative: Check if hasNextPage is explicitly set
        if (data.hasNextPage !== undefined) {
          setHasNextPage(data.hasNextPage);
        }

        // Update current cursor if not navigating back
        if (!isNavigatingBack) {
          setCurrentCursor(cursor);
        }

        setLastFetchTime(new Date());
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("❌ Failed to fetch eventOrder list:", error);
        }
        setErrors(error);
      } finally {
        setFetching(false);
        setRefreshing(false);
      }
    },
    [cid, eventOrderManager, onUnauthorized],
  );

  // Immediate filter application function
  const applyFilters = useCallback(() => {
    // Reset pagination when filters change
    setCursorHistory([]);
    setCurrentCursor("");
    setNextCursor("");
    setHasNextPage(false);
    // Clear cache and fetch fresh data
    eventOrderManager.clearEventOrdersCache();
    fetchEventOrderList("");
  }, [fetchEventOrderList, eventOrderManager]);

  // Refresh handler
  const handleRefresh = useCallback(() => {
    setRefreshing(true);
    applyFilters();
  }, [applyFilters]);

  // Pagination handlers
  const handleNextPage = useCallback(() => {
    if (hasNextPage && nextCursor) {
      // Push current cursor to history for "Previous" functionality
      setCursorHistory((prev) => [...prev, currentCursor]);

      // Fetch next page
      fetchEventOrderList(nextCursor);
    }
  }, [hasNextPage, nextCursor, currentCursor, fetchEventOrderList]);

  const handlePreviousPage = useCallback(() => {
    if (cursorHistory.length > 0) {
      // Pop the last cursor from history
      const newHistory = [...cursorHistory];
      const previousCursor = newHistory.pop();

      // Update history
      setCursorHistory(newHistory);

      // Fetch previous page
      fetchEventOrderList(previousCursor || "", true);
    }
  }, [cursorHistory, fetchEventOrderList]);

  // Handle page size change
  const handlePageSizeChange = useCallback(
    (e) => {
      const newPageSize = parseInt(e.target.value);
      setPageSize(newPageSize);
      // Apply filters immediately after state update
      setTimeout(() => applyFilters(), 0);
    },
    [pageSize, applyFilters],
  );

  // Handle sort change
  const handleSortChange = useCallback(
    (e) => {
      setSortByValue(e.target.value);
      // Apply filters immediately after state update
      setTimeout(() => applyFilters(), 0);
    },
    [applyFilters],
  );

  // Handle status filter change
  const handleStatusFilterChange = useCallback(
    (e) => {
      setStatus(parseInt(e.target.value));
      // Apply filters immediately after state update
      setTimeout(() => applyFilters(), 0);
    },
    [applyFilters],
  );

  // Format status helper with color
  const formatStatus = useCallback(
    (statusValue) => {
      const label = getEventOrderStatusLabel(statusValue);
      const variant = getEventOrderStatusVariant(statusValue);

      if (label === "Unknown") return <span>Unknown ({statusValue})</span>;

      const variantClasses = {
        success: getThemeClasses("stat-success"),
        secondary: getThemeClasses("text-secondary"),
      };

      return (
        <span
          className={`font-semibold ${variantClasses[variant] || variantClasses.secondary}`}
        >
          {label}
        </span>
      );
    },
    [getThemeClasses],
  );

  // Format event type helper with icon
  const formatEventType = useCallback((typeValue) => {
    const type = EVENT_TYPE_OPTIONS[typeValue];
    if (!type) return <span>Unknown ({typeValue})</span>;

    const IconComponent = type.icon;
    return (
      <span className="flex items-center">
        {IconComponent && <IconComponent className="w-4 h-4 mr-1" />}
        {type.label}
      </span>
    );
  }, []);

  // Format time since last fetch
  const formatLastFetchTime = useCallback(() => {
    if (!lastFetchTime) return null;
    const now = DateTime.now();
    const fetchTime = DateTime.fromJSDate(lastFetchTime);
    const diff = now.diff(fetchTime, ["minutes", "seconds"]);

    if (diff.minutes >= 1) {
      return `Last updated ${Math.floor(diff.minutes)} minute${Math.floor(diff.minutes) !== 1 ? "s" : ""} ago`;
    } else {
      return `Last updated ${Math.floor(diff.seconds)} seconds ago`;
    }
  }, [lastFetchTime]);

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
    }
  }, [authManager, navigate]);

  // Initial load - fetch customer detail
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchCustomerDetail();
    // Clear cache on mount to ensure fresh data
    eventOrderManager.clearEventOrdersCache();
  }, [cid, fetchCustomerDetail, eventOrderManager]);

  // Initial data load - only on mount
  useEffect(() => {
    if (cid && authManager.isAuthenticated()) {
      fetchEventOrderList("");
    }
  }, [cid, authManager, fetchEventOrderList]); // Include all dependencies

  // Page size options
  const pageSizeOptions = useMemo(
    () => [
      { value: 10, label: "10" },
      { value: 25, label: "25" },
      { value: 50, label: "50" },
      { value: 100, label: "100" },
      { value: 250, label: "250" },
    ],
    [],
  );

  // Status filter options
  const statusFilterOptions = useMemo(
    () => [
      { value: 0, label: "All Statuses" },
      { value: EVENT_ORDER_STATUS_ACTIVE, label: "Active" },
      { value: EVENT_ORDER_STATUS_ARCHIVED, label: "Archived" },
    ],
    [],
  );

  // Calculate pagination info
  const hasPreviousPage = useMemo(
    () => cursorHistory.length > 0,
    [cursorHistory],
  );
  const currentPageNumber = useMemo(
    () => cursorHistory.length + 1,
    [cursorHistory],
  );

  // Memoize theme classes
  const themeClasses = useMemo(
    () => ({
      borderPrimary: getThemeClasses("border.primary"),
      textSecondary: getThemeClasses("text.secondary"),
      textPrimary: getThemeClasses("text.primary"),
      bgPrimary: getThemeClasses("bg.primary"),
      bgPrimaryHover: getThemeClasses("bg.primaryHover"),
    }),
    [getThemeClasses],
  );

  if (isFetching && !customer.id) {
    return (
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="text-center">
            <div
              className={`animate-spin rounded-full h-12 w-12 border-b-2 ${themeClasses.borderPrimary} mx-auto`}
            ></div>
            <p className={`mt-4 ${themeClasses.textSecondary}`}>
              Loading customer eventOrders...
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <nav className="flex mb-6" aria-label="Breadcrumb">
        <ol className="inline-flex items-center space-x-1 md:space-x-3">
          <li className="inline-flex items-center">
            <Link
              to="/admin/dashboard"
              className={`inline-flex items-center text-sm font-medium ${getThemeClasses("text-primary")} ${getThemeClasses("link-hover")}`}
            >
              <ChartBarIcon className="w-4 h-4 mr-2" />
              Dashboard
            </Link>
          </li>
          <li>
            <div className="flex items-center">
              <span className={`mx-2 ${getThemeClasses("text-muted")}`}>/</span>
              <Link
                to="/admin/customers"
                className={`text-sm font-medium ${getThemeClasses("text-primary")} ${getThemeClasses("link-hover")}`}
              >
                <span className="inline-flex items-center">
                  <UserIcon className="w-4 h-4 mr-2" />
                  Customers
                </span>
              </Link>
            </div>
          </li>
          <li aria-current="page">
            <div className="flex items-center">
              <span className={`mx-2 ${getThemeClasses("text-muted")}`}>/</span>
              <span
                className={`text-sm font-medium ${getThemeClasses("text-secondary")} inline-flex items-center`}
              >
                <InformationCircleIcon className="w-4 h-4 mr-2" />
                Detail
              </span>
            </div>
          </li>
        </ol>
      </nav>

      {/* Page Title */}
      <div className="mb-6">
        <div className="flex justify-between items-center">
          <div>
            <h1
              className={`text-3xl font-bold ${getThemeClasses("text-primary")} flex items-center`}
            >
              <UserIcon
                className={`w-8 h-8 mr-3 ${getThemeClasses("text-info")}`}
              />
              Customer
            </h1>
            <p
              className={`mt-1 text-sm ${getThemeClasses("text-secondary")} flex items-center`}
            >
              <InformationCircleIcon className="w-4 h-4 mr-1" />
              View and manage eventOrders
            </p>
          </div>
        </div>
      </div>

      {/* Status Alerts */}
      {customer && customer.status === CUSTOMER_STATUS.ARCHIVED && (
        <div
          className={`mb-4 ${getThemeClasses("alert-info-bg")} ${getThemeClasses("alert-info-border")} ${getThemeClasses("alert-info-text")} px-4 py-3 rounded-lg flex items-center`}
        >
          <ArchiveBoxIcon className="w-5 h-5 mr-2" />
          This customer is archived
        </div>
      )}

      {customer && customer.isBanned && (
        <div
          className={`mb-4 ${getThemeClasses("alert-error-bg")} ${getThemeClasses("alert-error-border")} ${getThemeClasses("alert-error-text")} px-4 py-3 rounded-lg flex items-center`}
        >
          <BellAlertIcon className="w-5 h-5 mr-2" />
          This customer is banned
        </div>
      )}

      {/* Error Display */}
      {errors &&
        typeof errors === "object" &&
        Object.keys(errors).length > 0 && (
          <div
            className={`mb-4 ${getThemeClasses("alert-error-bg")} ${getThemeClasses("alert-error-border")} ${getThemeClasses("alert-error-text")} px-4 py-3 rounded-lg`}
          >
            <div className="flex items-start">
              <ExclamationTriangleIcon className="w-5 h-5 mr-2 mt-0.5" />
              <div className="flex-1">
                <strong>Error:</strong>
                <ul className="mt-2 list-disc list-inside">
                  {Object.entries(errors).map(([key, value]) => (
                    <li key={key}>
                      {key}: {Array.isArray(value) ? value.join(", ") : value}
                    </li>
                  ))}
                </ul>
              </div>
              <button
                onClick={() => setErrors({})}
                className={`${getThemeClasses("text-error")} ${getThemeClasses("text-error-dark")} ml-3`}
              >
                ×
              </button>
            </div>
          </div>
        )}

      {/* Main Content */}
      <div className="bg-white shadow-sm rounded-lg">
        {customer && (
          <>
            {/* Header with Title and Refresh Button */}
            <div
              className={`px-6 py-5 border-b ${getThemeClasses("border-color")}`}
            >
              <div className="flex justify-between items-center flex-wrap gap-4">
                <div className="flex items-center gap-4">
                  <h2
                    className={`text-2xl font-semibold ${getThemeClasses("text-primary")} flex items-center`}
                  >
                    <WrenchScrewdriverIcon
                      className={`w-7 h-7 mr-2 ${getThemeClasses("text-info")}`}
                    />
                    Event Orders
                  </h2>
                  {lastFetchTime && (
                    <span
                      className={`text-sm ${getThemeClasses("text-secondary")} flex items-center`}
                    >
                      <ClockIcon className="w-4 h-4 mr-1" />
                      {formatLastFetchTime()}
                    </span>
                  )}
                </div>
                <div className="flex gap-3">
                  <Link
                    to={`/admin/event-orders/add?customer_id=${cid}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    <button
                      className={`inline-flex items-center px-5 py-2.5 border border-transparent rounded-lg text-base font-medium ${getThemeClasses("button-success")}`}
                    >
                      <PlusIcon className="w-5 h-5 mr-2" />
                      New Event Order
                    </button>
                  </Link>
                  <button
                    onClick={handleRefresh}
                    disabled={isRefreshing}
                    className={`inline-flex items-center px-5 py-2.5 rounded-lg text-base font-medium transition-colors disabled:opacity-50 ${getThemeClasses("button-outline")}`}
                  >
                    <ArrowPathIcon
                      className={`w-5 h-5 mr-2 ${isRefreshing ? "animate-spin" : ""}`}
                    />
                    {isRefreshing ? "Refreshing..." : "Refresh"}
                  </button>
                </div>
              </div>
            </div>

            {/* Tab Navigation */}
            <div className={`px-6 border-b ${getThemeClasses("border-color")}`}>
              <nav className="-mb-px flex space-x-8">
                <Link
                  to={`/admin/customer/${cid}`}
                  className={`border-b-2 border-transparent py-4 px-1 text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("tab-hover")}`}
                >
                  Summary
                </Link>
                <Link
                  to={`/admin/customer/${cid}/detail`}
                  className={`border-b-2 border-transparent py-4 px-1 text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("tab-hover")}`}
                >
                  Detail
                </Link>
                <div
                  className={`border-b-2 ${getThemeClasses("border-info")} py-4 px-1 text-base font-medium ${getThemeClasses("text-info")}`}
                >
                  Event Orders
                </div>
                <Link
                  to={`/admin/customer/${cid}/comments`}
                  className={`border-b-2 border-transparent py-4 px-1 text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("tab-hover")}`}
                >
                  Comments
                </Link>
                <Link
                  to={`/admin/customer/${cid}/attachments`}
                  className={`border-b-2 border-transparent py-4 px-1 text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("tab-hover")}`}
                >
                  Attachments
                </Link>
                <Link
                  to={`/admin/customer/${cid}/more`}
                  className={`border-b-2 border-transparent py-4 px-1 text-base font-medium ${getThemeClasses("text-secondary")} ${getThemeClasses("tab-hover")} inline-flex items-center`}
                >
                  More
                  <EllipsisHorizontalIcon className="w-5 h-5 ml-1" />
                </Link>
              </nav>
            </div>

            <div className="p-6">
              {/* Filters Section */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div>
                  <label
                    className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}
                  >
                    Status Filter:
                  </label>
                  <select
                    value={status}
                    onChange={handleStatusFilterChange}
                    className={`block w-full px-3 py-2 border rounded-lg ${getThemeClasses("input-focus")} ${getThemeClasses("border-color")}`}
                  >
                    {statusFilterOptions.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div>
                  <label
                    className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}
                  >
                    Sort By:
                  </label>
                  <select
                    value={sortByValue}
                    onChange={handleSortChange}
                    className={`block w-full px-3 py-2 border rounded-lg ${getThemeClasses("input-focus")} ${getThemeClasses("border-color")}`}
                  >
                    <option value="created_at,DESC">
                      Created Date (Newest)
                    </option>
                    <option value="created_at,ASC">
                      Created Date (Oldest)
                    </option>
                    <option value="assignment_date,DESC">
                      Assignment Date (Newest)
                    </option>
                    <option value="assignment_date,ASC">
                      Assignment Date (Oldest)
                    </option>
                    <option value="start_date,DESC">Start Date (Newest)</option>
                    <option value="start_date,ASC">Start Date (Oldest)</option>
                  </select>
                </div>

                <div>
                  <label
                    className={`block text-sm font-medium ${getThemeClasses("text-primary")} mb-2`}
                  >
                    Items per page:
                  </label>
                  <select
                    value={pageSize}
                    onChange={handlePageSizeChange}
                    className={`block w-full px-3 py-2 border rounded-lg ${getThemeClasses("input-focus")} ${getThemeClasses("border-color")}`}
                  >
                    {pageSizeOptions.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Results Count */}
              <div className={`mb-6 ${getThemeClasses("text-secondary")}`}>
                Showing{" "}
                <strong className={getThemeClasses("text-primary")}>
                  {eventOrderList.results ? eventOrderList.results.length : 0}
                </strong>{" "}
                eventOrders
                {totalCount > 0 && ` (Total: ${totalCount})`}
                {status !== 0 && ` (filtered by status)`}
              </div>

              {/* EventOrders List */}
              {isFetching || isRefreshing ? (
                <div className="flex items-center justify-center py-12">
                  <div className="text-center">
                    <div
                      className={`animate-spin rounded-full h-10 w-10 border-b-2 ${getThemeClasses("border-info")} mx-auto`}
                    ></div>
                    <p className={`mt-4 ${getThemeClasses("text-secondary")}`}>
                      {isRefreshing
                        ? "Refreshing eventOrders..."
                        : "Loading eventOrders..."}
                    </p>
                  </div>
                </div>
              ) : eventOrderList &&
                eventOrderList.results &&
                (eventOrderList.results.length > 0 ||
                  cursorHistory.length > 0) ? (
                <>
                  {/* EventOrders Table - Desktop */}
                  <div className="hidden md:block overflow-x-auto">
                    <table
                      className={`min-w-full divide-y ${getThemeClasses("border-color")}`}
                    >
                      <thead className={getThemeClasses("table-header-bg")}>
                        <tr>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Event #
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Event Name
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Event Type
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Start Date
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            End Date
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Attendees
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Status
                          </th>
                          <th
                            className={`px-6 py-3 text-left text-xs font-medium ${getThemeClasses("text-secondary")} uppercase tracking-wider`}
                          >
                            Actions
                          </th>
                        </tr>
                      </thead>
                      <tbody
                        className={`bg-white divide-y ${getThemeClasses("border-color")}`}
                      >
                        {eventOrderList.results.map((eventOrder, index) => (
                          <tr
                            key={eventOrder.eventPublicId || index}
                            className={
                              index % 2 === 0
                                ? "bg-white"
                                : getThemeClasses("table-row-alt")
                            }
                          >
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm font-mono ${getThemeClasses("text-primary")}`}
                            >
                              #
                              {eventOrder.public_id || eventOrder.eventPublicId}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")}`}
                            >
                              <div className="font-medium">
                                {eventOrder.eventName}
                              </div>
                              {eventOrder.eventDescription && (
                                <div
                                  className={`text-xs ${getThemeClasses("text-secondary")} truncate max-w-xs`}
                                >
                                  {eventOrder.eventDescription}
                                </div>
                              )}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")}`}
                            >
                              {formatEventType(eventOrder.eventType)}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")}`}
                            >
                              {formatDateForDisplay(
                                eventOrder.eventStartDateTime,
                              )}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")}`}
                            >
                              {formatDateForDisplay(
                                eventOrder.eventEndDateTime,
                              )}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")} text-center`}
                            >
                              {eventOrder.eventAttendeeCapacity || "-"}
                            </td>
                            <td className="px-6 py-4 whitespace-nowrap text-sm">
                              {formatStatus(eventOrder.status)}
                            </td>
                            <td
                              className={`px-6 py-4 whitespace-nowrap text-sm ${getThemeClasses("text-primary")}`}
                            >
                              <Link
                                to={`/admin/event-order/${eventOrder.id}`}
                                className={`${getThemeClasses("text-info")} ${getThemeClasses("link-hover")} inline-flex items-center`}
                              >
                                View
                                <ArrowRightIcon className="w-3 h-3 ml-1" />
                              </Link>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>

                  {/* EventOrders List - Mobile */}
                  <div className="md:hidden space-y-4">
                    {eventOrderList.results.map((eventOrder, index) => (
                      <div
                        key={eventOrder.id || index}
                        className={`${getThemeClasses("card-bg")} rounded-lg border ${getThemeClasses("border-color")} p-4`}
                      >
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            Event #:
                          </strong>{" "}
                          <span className="font-mono">
                            #{eventOrder.publicId || eventOrder.eventPublicId}
                          </span>
                        </div>
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            Event Name:
                          </strong>{" "}
                          <div className="font-medium">
                            {eventOrder.eventName}
                          </div>
                          {eventOrder.eventDescription && (
                            <div
                              className={`text-sm ${getThemeClasses("text-secondary")} mt-1`}
                            >
                              {eventOrder.eventDescription}
                            </div>
                          )}
                        </div>
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            Event Type:
                          </strong>{" "}
                          {formatEventType(eventOrder.eventType)}
                        </div>
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            Start Date:
                          </strong>{" "}
                          {formatDateForDisplay(eventOrder.eventStartDateTime)}
                        </div>
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            End Date:
                          </strong>{" "}
                          {formatDateForDisplay(eventOrder.eventEndDateTime)}
                        </div>
                        <div className="mb-3">
                          <strong className={getThemeClasses("text-primary")}>
                            Attendees:
                          </strong>{" "}
                          {eventOrder.event_attendee_capacity || "-"}
                        </div>
                        <div className="mb-4">
                          <strong className={getThemeClasses("text-primary")}>
                            Status:
                          </strong>{" "}
                          {formatStatus(eventOrder.status)}
                        </div>
                        <Link to={`/admin/event-order/${eventOrder.id}`}>
                          <button
                            className={`w-full inline-flex items-center justify-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium ${getThemeClasses("button-primary")}`}
                          >
                            View Event Order
                            <ArrowRightIcon className="w-4 h-4 ml-2" />
                          </button>
                        </Link>
                      </div>
                    ))}
                  </div>

                  {/* Pagination Controls */}
                  {(hasPreviousPage || hasNextPage) && (
                    <div
                      className={`flex justify-between items-center pt-6 border-t ${getThemeClasses("border-color")} mt-6`}
                    >
                      <div
                        className={`flex items-center text-sm ${getThemeClasses("text-primary")}`}
                      >
                        Page {currentPageNumber}
                        {totalCount > 0 && (
                          <span
                            className={`ml-2 ${getThemeClasses("text-secondary")}`}
                          >
                            (Total: {totalCount} eventOrders)
                          </span>
                        )}
                      </div>
                      <div className="flex gap-3">
                        {hasPreviousPage && (
                          <button
                            onClick={handlePreviousPage}
                            className={`inline-flex items-center px-4 py-2 rounded-lg text-sm font-medium transition-colors ${getThemeClasses("button-outline")}`}
                          >
                            <ChevronLeftIcon className="w-4 h-4 mr-2" />
                            Previous
                          </button>
                        )}
                        {hasNextPage && (
                          <button
                            onClick={handleNextPage}
                            className={`inline-flex items-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium transition-colors ${getThemeClasses("button-primary")}`}
                          >
                            Next
                            <ChevronRightIcon className="w-4 h-4 ml-2" />
                          </button>
                        )}
                      </div>
                    </div>
                  )}
                </>
              ) : (
                // No eventOrders message
                <div
                  className={`text-center py-16 ${getThemeClasses("card-bg")} rounded-lg`}
                >
                  <UserGroupIcon
                    className={`w-12 h-12 ${getThemeClasses("text-muted")} mx-auto mb-4`}
                  />
                  <h3
                    className={`text-lg font-medium ${getThemeClasses("text-primary")} mb-2`}
                  >
                    No Event Orders Found
                  </h3>
                  <p className={`${getThemeClasses("text-secondary")} mb-6`}>
                    {status !== 0
                      ? "No event orders match the selected status filter."
                      : "No event orders found for this customer."}
                  </p>
                  {customer && (
                    <Link
                      to={`/admin/event-orders/add?customer_id=${cid}`}
                      target="_blank"
                      rel="noreferrer"
                    >
                      <button
                        className={`inline-flex items-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium transition-colors ${getThemeClasses("button-success")}`}
                      >
                        <PlusIcon className="w-4 h-4 mr-2" />
                        Create First Event Order
                      </button>
                    </Link>
                  )}
                </div>
              )}

              {/* Action Buttons */}
              <div
                className={`flex justify-between mt-8 pt-6 border-t ${getThemeClasses("border-color")}`}
              >
                <Link to="/admin/customers">
                  <button
                    className={`inline-flex items-center px-5 py-2.5 rounded-lg text-base font-medium transition-colors ${getThemeClasses("button-outline")}`}
                  >
                    <ChevronLeftIcon className="w-5 h-5 mr-2" />
                    Back to Customers
                  </button>
                </Link>
                {customer && (
                  <Link
                    to={`/admin/event-orders/add?customer_id=${cid}`}
                    target="_blank"
                    rel="noreferrer"
                  >
                    <button
                      className={`inline-flex items-center px-5 py-2.5 border border-transparent rounded-lg text-base font-medium transition-colors ${getThemeClasses("button-success")}`}
                    >
                      <PlusIcon className="w-5 h-5 mr-2" />
                      New Event Order
                    </button>
                  </Link>
                )}
              </div>
            </div>
          </>
        )}

        {!customer && !isFetching && (
          <div className="px-6 py-16 text-center">
            <div
              className={`inline-flex items-center justify-center w-16 h-16 ${getThemeClasses("card-bg")} rounded-full mb-4`}
            >
              <UserIcon
                className={`w-8 h-8 ${getThemeClasses("text-muted")}`}
              />
            </div>
            <h3
              className={`text-lg font-medium ${getThemeClasses("text-primary")} mb-2`}
            >
              Customer Not Found
            </h3>
            <p className={`${getThemeClasses("text-secondary")} mb-6`}>
              The customer you're looking for doesn't exist or you don't have
              permission to view it.
            </p>
            <Link to="/admin/customers">
              <button
                className={`inline-flex items-center px-4 py-2 border border-transparent rounded-lg text-sm font-medium transition-colors ${getThemeClasses("button-primary")}`}
              >
                <ChevronLeftIcon className="w-4 h-4 mr-2" />
                Back to Customers
              </button>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}

export default AdminCustomerDetailEventOrderListPage;
