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

import React, { useState, useEffect, useCallback, useRef } from "react";
import { Link, useNavigate, useLocation } from "react-router";
import {
  useEventOrderManager,
  useEventManager,
  useCustomerManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  EVENT_ORDER_STATUS_OPTIONS,
  getEventOrderStatusLabel,
  getEventOrderStatusVariant,
} from "../../../../constants/EventOrder";
import {
  UIXThemeProvider,
  useUIXTheme,
  DataList,
  Breadcrumb,
  Badge,
  Button,
  Modal,
  Alert,
  DetailPageIcon,
  ViewButton,
  Card,
} from "../../../../components/UIX";
import {
  TicketIcon,
  PlusIcon,
  MagnifyingGlassIcon,
  FunnelIcon,
  ArrowPathIcon,
  ChevronRightIcon,
  XMarkIcon,
  ArchiveBoxIcon,
  PencilSquareIcon,
  EyeIcon,
  ExclamationTriangleIcon,
  ChartBarIcon,
  ClipboardDocumentListIcon,
  CheckCircleIcon,
  UserIcon,
  CalendarIcon,
  CalendarDaysIcon,
  ClockIcon,
  CurrencyDollarIcon,
  DocumentTextIcon,
  Squares2X2Icon,
  TableCellsIcon,
  ChevronDownIcon,
  UserGroupIcon,
  TagIcon,
  HashtagIcon,
  HomeIcon,
  ArrowLeftIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
} from "@heroicons/react/24/outline";
import {
  formatDateForDisplay,
  formatDateTime,
} from "../../../../services/Helpers/DateFormatter";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";

// Constants for filtering and sorting imported from EventOrder constants

const EVENT_ORDER_SORT_OPTIONS = [
  { value: "created_at,DESC", label: "Created Date (Newest → Oldest)" },
  { value: "created_at,ASC", label: "Created Date (Oldest → Newest)" },
  {
    value: "event_start_date_time,DESC",
    label: "Event Date (Newest → Oldest)",
  },
  { value: "event_start_date_time,ASC", label: "Event Date (Oldest → Newest)" },
  { value: "customer_lexical_name,ASC", label: "Customer Name (A → Z)" },
  { value: "customer_lexical_name,DESC", label: "Customer Name (Z → A)" },
];


const VIEW_TYPE_TABULAR = "tabular";
const VIEW_TYPE_GRID = "grid";

const DEFAULT_PAGE = 1;
const DEFAULT_PAGE_SIZE = 25;

function AdminEventOrderListPage() {
  return (
    <UIXThemeProvider>
      <AdminEventOrderListPageContent />
    </UIXThemeProvider>
  );
}

function AdminEventOrderListPageContent() {
  const { getThemeClasses } = useUIXTheme();
  const eventOrderManager = useEventOrderManager();
  const eventManager = useEventManager();
  const customerManager = useCustomerManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const location = useLocation();
  const isLoadingRef = useRef(false);

  // Main state
  const [eventOrders, setEventOrders] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [successMessage, setSuccessMessage] = useState("");
  const [totalCount, setTotalCount] = useState(0);

  // Pagination state
  const [currentPage, setCurrentPage] = useState(DEFAULT_PAGE);
  const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
  const [hasNextPage, setHasNextPage] = useState(false);

  // Filter and search state
  const [searchTerm, setSearchTerm] = useState("");
  const [tempSearchTerm, setTempSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [sortBy, setSortBy] = useState("created_at,DESC");
  const [viewType, setViewType] = useState(VIEW_TYPE_GRID);

  // Additional filters
  const [selectedEventId, setSelectedEventId] = useState("");
  const [selectedCustomerId, setSelectedCustomerId] = useState("");
  const [eventStartDateFrom, setEventStartDateFrom] = useState("");
  const [eventStartDateTo, setEventStartDateTo] = useState("");

  // Select options state
  const [events, setEvents] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [loadingSelectOptions, setLoadingSelectOptions] = useState(false);

  // Delete/Archive confirmation modal
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [eventOrderToDelete, setEventOrderToDelete] = useState(null);

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };

  // Load select options for events and customers
  const loadSelectOptions = useCallback(async () => {
    setLoadingSelectOptions(true);
    try {
      // Load events for filter dropdown
      const eventsResponse = await eventManager.getEvents(
        { limit: 100, status: "active" },
        onUnauthorized,
        false,
      );
      if (eventsResponse?.results) {
        setEvents(eventsResponse.results);
      }

      // Load customers for filter dropdown
      const customersResponse = await customerManager.getCustomers(
        { limit: 100, status: "1" }, // Active customers
        onUnauthorized,
        false,
      );
      if (customersResponse?.results) {
        setCustomers(customersResponse.results);
      }
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to load select options:", err);
      }
    } finally {
      setLoadingSelectOptions(false);
    }
  }, [eventManager, customerManager]);

  // Fetch event orders using the manager
  const fetchEventOrders = useCallback(
    async (params = {}) => {
      // Extract forceRefresh from params (default to false)
      const { forceRefresh = false, ...otherParams } = params;

      // Prevent double loading
      if (isLoadingRef.current && !forceRefresh) {
        return;
      }

      try {
        isLoadingRef.current = true;
        setIsLoading(true);
        setErrors({});

        // Parse sort parameter
        const [sortField, sortOrderString] = sortBy.split(",");
        const sortOrder = sortOrderString === "DESC" ? -1 : 1;

        // Build query params
        const queryParams = {
          page: currentPage,
          limit: pageSize,
          sortField,
          sortOrder,
          search: searchTerm.trim(),
          excludeArchived: true,
          ...otherParams,
        };

        // Add optional filters
        if (statusFilter) queryParams.status = statusFilter;
        if (selectedEventId) queryParams.eventId = selectedEventId;
        if (selectedCustomerId) queryParams.customerId = selectedCustomerId;
        if (eventStartDateFrom) queryParams.eventStartDateFrom = eventStartDateFrom;
        if (eventStartDateTo) queryParams.eventStartDateTo = eventStartDateTo;

        // Remove empty params
        Object.keys(queryParams).forEach((key) => {
          if (!queryParams[key] && queryParams[key] !== 0) {
            delete queryParams[key];
          }
        });

        const response = await eventOrderManager.getEventOrders(
          queryParams,
          onUnauthorized,
          forceRefresh,
        );

        if (response?.results) {
          setEventOrders(response.results);
          setTotalCount(response.count || 0);
          setHasNextPage(response.hasNextPage || false);
        } else {
          setEventOrders([]);
          setTotalCount(0);
          setHasNextPage(false);
        }
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch event orders:", err);
        }
        setErrors({ fetch: "Failed to load event orders. Please try again." });
        setEventOrders([]);
        setTotalCount(0);
        setHasNextPage(false);
      } finally {
        setIsLoading(false);
        isLoadingRef.current = false;
      }
    },
    [
      eventOrderManager,
      currentPage,
      pageSize,
      searchTerm,
      sortBy,
      statusFilter,
      selectedEventId,
      selectedCustomerId,
      eventStartDateFrom,
      eventStartDateTo,
    ],
  );

  // Handle search
  const handleSearch = useCallback(() => {
    setSearchTerm(tempSearchTerm);
    setCurrentPage(1);
  }, [tempSearchTerm]);

  // Handle filter changes
  const handleFilterChange = useCallback(() => {
    setCurrentPage(1);
  }, []);

  // Handle sort change
  const handleSortChange = useCallback((newSortBy) => {
    setSortBy(newSortBy);
    setCurrentPage(1);
  }, []);

  // Handle page change
  const handlePageChange = useCallback((page) => {
    setCurrentPage(page);
  }, []);

  // Handle page size change
  const handlePageSizeChange = useCallback((newPageSize) => {
    setPageSize(newPageSize);
    setCurrentPage(1);
  }, []);

  // Handle delete/archive event order
  const handleDelete = useCallback(async () => {
    if (!eventOrderToDelete) return;

    try {
      setIsLoading(true);
      await eventOrderManager.deleteEventOrder(
        eventOrderToDelete.id,
        onUnauthorized,
      );
      setSuccessMessage("Event order deleted successfully");
      setShowDeleteModal(false);
      setEventOrderToDelete(null);
      fetchEventOrders({ forceRefresh: true });
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to delete event order:", err);
      }
      setErrors({ delete: "Failed to delete event order. Please try again." });
    } finally {
      setIsLoading(false);
    }
  }, [eventOrderToDelete, eventOrderManager, fetchEventOrders]);

  // Initial load
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login?unauthorized=true");
      return;
    }
    loadSelectOptions();
  }, [authManager, navigate, loadSelectOptions]);

  // Fetch data when dependencies change or when landing on this page
  useEffect(() => {
    if (authManager.isAuthenticated()) {
      fetchEventOrders({ forceRefresh: true });
    }
  }, [authManager, fetchEventOrders, location.pathname]);

  // Handle success message from navigation state
  useEffect(() => {
    if (location.state?.successMessage) {
      setSuccessMessage(location.state.successMessage);
      window.history.replaceState({}, document.title);
      setTimeout(() => setSuccessMessage(""), 3000);
    }
  }, [location]);

  // Use the EventOrder status variant function
  const getStatusBadgeColor = getEventOrderStatusVariant;

  // Use the EventOrder status formatting function
  const formatStatus = getEventOrderStatusLabel;

  // Column configuration for DataList
  const columns = [
    {
      key: "publicId",
      header: "Order #",
      sortable: true,
      render: (value, eventOrder) => (
        <Link
          to={`/admin/event-order/${eventOrder.id}`}
          className={`${getThemeClasses("text-primary")} hover:${getThemeClasses("text-primary-dark")} font-medium flex items-center transition-colors`}
        >
          <HashtagIcon className="w-4 h-4 mr-1 flex-shrink-0" />
          <span className="truncate">{value || eventOrder.id}</span>
        </Link>
      ),
    },
    {
      key: "eventName",
      header: "Event",
      sortable: true,
      render: (value, eventOrder) => (
        <div className="flex items-center">
          <CalendarIcon className="w-4 h-4 mr-2 text-gray-400 flex-shrink-0" />
          <div className="min-w-0">
            <div className="text-sm font-medium text-gray-900 truncate">
              {value || "N/A"}
            </div>
            {eventOrder.eventStartDateTime && (
              <div className="text-xs text-gray-500">
                {formatDateTime(eventOrder.eventStartDateTime)}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      key: "customerName",
      header: "Customer",
      sortable: true,
      render: (value, eventOrder) => (
        <div className="flex items-center">
          <UserIcon className="w-4 h-4 mr-2 text-gray-400 flex-shrink-0" />
          <div className="min-w-0">
            <div className="text-sm text-gray-900 truncate">
              {value || "N/A"}
            </div>
            {eventOrder.customerOrganizationName && (
              <div className="text-xs text-gray-500 truncate">
                {eventOrder.customerOrganizationName}
                {eventOrder.customerDivisionName && ` - ${eventOrder.customerDivisionName}`}
              </div>
            )}
            {eventOrder.customerEmail && (
              <div className="text-xs text-gray-500 truncate">
                {eventOrder.customerEmail}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      key: "totalAmount",
      header: "Amount",
      sortable: true,
      render: (value) => (
        <div className="flex items-center">
          <CurrencyDollarIcon className="w-4 h-4 mr-1 text-gray-400 flex-shrink-0" />
          <span className="text-sm font-medium text-gray-900">
            {value ? `$${parseFloat(value).toFixed(2)}` : "N/A"}
          </span>
        </div>
      ),
    },
    {
      key: "status",
      header: "Status",
      sortable: true,
      render: (value) => (
        <Badge
          variant={getEventOrderStatusVariant(value)}
          size="sm"
        >
          {getEventOrderStatusLabel(value)}
        </Badge>
      ),
    },
    {
      key: "createdAt",
      header: "Created",
      sortable: true,
      render: (value) => (
        <div className="text-sm text-gray-500">
          {value ? formatDateForDisplay(value) : "N/A"}
        </div>
      ),
    },
    {
      key: "actions",
      header: "Actions",
      sortable: false,
      render: (_, eventOrder) => (
        <div className="flex items-center space-x-2">
          <Link
            to={`/admin/event-order/${eventOrder.id}`}
            className="text-blue-600 hover:text-blue-800 transition-colors"
            title="View details"
          >
            <EyeIcon className="w-4 h-4" />
          </Link>
          <Link
            to={`/admin/event-order/${eventOrder.id}/update`}
            className="text-green-600 hover:text-green-800 transition-colors"
            title="Edit order"
          >
            <PencilSquareIcon className="w-4 h-4" />
          </Link>
          <button
            onClick={(e) => {
              e.stopPropagation();
              setEventOrderToDelete(eventOrder);
              setShowDeleteModal(true);
            }}
            className="text-red-600 hover:text-red-800 transition-colors"
            title="Delete order"
          >
            <XMarkIcon className="w-4 h-4" />
          </button>
        </div>
      ),
    },
  ];

  // Extended filters configuration
  const extendedFilters = [
    {
      type: "select",
      key: "selectedEventId",
      label: "Event",
      value: selectedEventId,
      onChange: (value) => {
        setSelectedEventId(value);
        handleFilterChange();
      },
      options: [
        { value: "", label: "All Events" },
        ...events.map((event) => ({
          value: event.id,
          label: event.name,
        })),
      ],
      disabled: loadingSelectOptions,
    },
    {
      type: "select",
      key: "selectedCustomerId",
      label: "Customer",
      value: selectedCustomerId,
      onChange: (value) => {
        setSelectedCustomerId(value);
        handleFilterChange();
      },
      options: [
        { value: "", label: "All Customers" },
        ...customers.map((customer) => ({
          value: customer.id,
          label: customer.name || `${customer.firstName} ${customer.lastName}`,
        })),
      ],
      disabled: loadingSelectOptions,
    },
    {
      type: "date",
      key: "eventStartDateFrom",
      label: "Event Date (From)",
      value: eventStartDateFrom,
      onChange: (value) => {
        setEventStartDateFrom(value);
        handleFilterChange();
      },
    },
    {
      type: "date",
      key: "eventStartDateTo",
      label: "Event Date (To)",
      value: eventStartDateTo,
      onChange: (value) => {
        setEventStartDateTo(value);
        handleFilterChange();
      },
    },
  ];

  return (
    <>
      {/* Breadcrumb */}
      <Breadcrumb items={[
        {
          label: 'Dashboard',
          to: '/admin/dashboard',
          icon: HomeIcon
        },
        {
          label: 'Event Orders',
          icon: TicketIcon,
          isActive: true
        }
      ]} />

      {/* Conditional Rendering: DataList for table view, Custom Grid for card view */}
      {viewType === VIEW_TYPE_TABULAR ? (
        <DataList
          data={eventOrders}
          columns={columns}
          isLoading={isLoading}
          errors={errors}
          successMessage={successMessage}
          onSuccessMessageClose={() => setSuccessMessage("")}
          searchFilter={{
            searchTerm,
            tempSearchTerm,
            onSearchTermChange: setTempSearchTerm,
            onSearchSubmit: handleSearch,
            placeholder: "Search by order #, event name, customer...",
            basicFilters: [
              {
                type: "select",
                key: "status",
                label: "Status",
                value: statusFilter,
                onChange: (value) => {
                  setStatusFilter(value);
                  handleFilterChange();
                },
                options: EVENT_ORDER_STATUS_OPTIONS,
              },
              {
                type: "select",
                key: "sortBy",
                label: "Sort By",
                value: sortBy,
                onChange: handleSortChange,
                options: EVENT_ORDER_SORT_OPTIONS,
              },
              {
                type: "select",
                key: "pageSize",
                label: "Per Page",
                value: pageSize.toString(),
                onChange: (value) => handlePageSizeChange(parseInt(value)),
                options: PAGE_SIZE_OPTIONS,
              },
            ],
            extendedFilters,
          }}
          pagination={{
            currentPage,
            totalPages: Math.ceil(totalCount / pageSize),
            hasNextPage,
            pageSize,
            totalCount,
            onPageChange: handlePageChange,
            onPageSizeChange: handlePageSizeChange,
          }}
          emptyState={{
            icon: TicketIcon,
            title: "No Event Orders Found",
            description: searchTerm || statusFilter || selectedEventId || selectedCustomerId
              ? "No event orders match your current filters. Try adjusting your search criteria."
              : "No event orders have been added yet.",
            actionLabel: "Create Order",
            onActionClick: () => navigate("/admin/event-orders/add/step-1-search"),
            isCreateAction: true
          }}
          header={{
            icon: TicketIcon,
            title: "Event Order Management",
            showHeader: true,
            subtitle: "Manage event orders, bookings, and customer transactions",
            decorativeIcon: <DetailPageIcon icon={TicketIcon} />,
            actions: [
              <div key="view-toggle" className="flex items-center gap-1">
                <Button
                  variant={viewType === VIEW_TYPE_TABULAR ? "primary" : "ghost"}
                  onClick={() => setViewType(VIEW_TYPE_TABULAR)}
                  size="sm"
                >
                  <TableCellsIcon className="w-5 h-5" />
                </Button>
                <Button
                  variant={viewType === VIEW_TYPE_GRID ? "primary" : "ghost"}
                  onClick={() => setViewType(VIEW_TYPE_GRID)}
                  size="sm"
                >
                  <Squares2X2Icon className="w-5 h-5" />
                </Button>
              </div>,
              <Button
                key="search"
                variant="secondary"
                size="md"
                onClick={() => navigate("/admin/event-orders/search")}
                icon={ArrowLeftIcon}
              >
                Advanced Search
              </Button>,
              <Button
                key="add"
                variant="success"
                size="lg"
                onClick={() => navigate("/admin/event-orders/add/step-1-search")}
                icon={PlusIcon}
              >
                Create Order
              </Button>
            ]
          }}
        />
      ) : (
        /* Standalone Grid View - Exactly matching DataList structure */
        <div className={`min-h-screen ${getThemeClasses('bg-gradient-primary')}`}>
          {/* Decorative background elements */}
          <div className="fixed inset-0 overflow-hidden pointer-events-none">
            <div className="absolute -top-40 -right-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob"></div>
            <div className="absolute -bottom-40 -left-40 w-80 h-80 bg-yellow-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000"></div>
            <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000"></div>
          </div>

          <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8 lg:py-12">
            {/* Success Message */}
            {successMessage && (
              <div className={`mb-6 sm:mb-8 p-4 ${getThemeClasses('success-bg')} border ${getThemeClasses('success-border')} rounded-lg flex items-center`}>
                <span className={`text-sm ${getThemeClasses('success-text')}`}>{successMessage}</span>
                <button
                  onClick={() => setSuccessMessage("")}
                  className={`ml-auto ${getThemeClasses('success-text')} hover:opacity-75`}
                >
                  ×
                </button>
              </div>
            )}

            {/* Main Content Layout - Centered */}
            <div className="max-w-7xl mx-auto">
              <div className="bg-white shadow-xl rounded-2xl overflow-hidden border border-gray-100 hover:shadow-2xl transition-shadow duration-300">

                {/* Header Section - Inside the white card */}
                <div className={`px-6 sm:px-8 py-6 border-b ${getThemeClasses('border-secondary')}`}>
                  <div className="flex flex-col space-y-4 lg:flex-row lg:items-start lg:justify-between lg:space-y-0">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start">
                        <div className={`p-3 rounded-2xl shadow-lg mr-4 flex-shrink-0 ${getThemeClasses('bg-gradient-secondary')}`}>
                          <TicketIcon className="h-8 w-8 sm:h-10 sm:w-10 text-white" />
                        </div>
                        <div className="text-center lg:text-left">
                          <h1 className={`text-2xl sm:text-3xl lg:text-4xl font-bold ${getThemeClasses('text-primary')} leading-tight`}>
                            Event Order Management
                          </h1>
                        </div>
                      </div>
                    </div>
                    <div className="flex-shrink-0 flex items-center gap-3">
                      <div className="flex items-center gap-1">
                        <Button
                          variant={viewType === VIEW_TYPE_TABULAR ? "primary" : "ghost"}
                          onClick={() => setViewType(VIEW_TYPE_TABULAR)}
                          size="sm"
                        >
                          <TableCellsIcon className="w-5 h-5" />
                        </Button>
                        <Button
                          variant={viewType === VIEW_TYPE_GRID ? "primary" : "ghost"}
                          onClick={() => setViewType(VIEW_TYPE_GRID)}
                          size="sm"
                        >
                          <Squares2X2Icon className="w-5 h-5" />
                        </Button>
                      </div>
                      <Button
                        variant="secondary"
                        size="md"
                        onClick={() => navigate("/admin/event-orders/search")}
                        icon={ArrowLeftIcon}
                      >
                        Advanced Search
                      </Button>
                      <Button
                        variant="success"
                        size="lg"
                        onClick={() => navigate("/admin/event-orders/add/step-1-search")}
                        icon={PlusIcon}
                      >
                        Create Order
                      </Button>
                    </div>
                  </div>
                </div>

                {/* Content continues with grid view implementation */}
                <div className="p-6">
                  {isLoading ? (
                    <div className="flex items-center justify-center py-12">
                      <div className={`animate-spin rounded-full h-12 w-12 border-b-2 ${getThemeClasses('border-primary')}`}></div>
                      <span className={`ml-3 ${getThemeClasses('text-secondary')}`}>Loading...</span>
                    </div>
                  ) : eventOrders?.length > 0 ? (
                    <>
                      {/* Results count */}
                      <div className={`mb-6 text-sm ${getThemeClasses('text-secondary')}`}>
                        Showing <strong>{eventOrders.length}</strong> orders
                        {totalCount > 0 && ` of ${totalCount} total`}
                        {searchTerm && ` (filtered by "${searchTerm}")`}
                      </div>

                      {/* Grid View */}
                      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        {eventOrders.map((order) => (
                          <div
                            key={order.id}
                            className={`bg-white border ${getThemeClasses('card-border')} rounded-lg shadow-sm hover:shadow-lg transition-shadow cursor-pointer`}
                            onClick={() => navigate(`/admin/event-order/${order.id}`)}
                          >
                            <div className="p-6">
                              <div className="mb-4">
                                <h3 className={`text-lg font-semibold ${getThemeClasses('text-primary')} flex items-start`}>
                                  <HashtagIcon className={`w-5 h-5 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses('text-muted')}`} />
                                  <span>Order #{order.publicId || order.id}</span>
                                </h3>
                                <div className="mt-2 text-sm space-y-1">
                                  <div>
                                    <Badge
                                      variant={getEventOrderStatusVariant(order.status)}
                                      size="sm"
                                    >
                                      {getEventOrderStatusLabel(order.status)}
                                    </Badge>
                                  </div>
                                </div>
                              </div>

                              <div className={`space-y-2 text-base ${getThemeClasses('text-primary')} mb-4`}>
                                <div className="flex items-center">
                                  <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                  <span className="truncate">
                                    {order.eventName || "N/A"}
                                  </span>
                                </div>
                                <div className="flex items-start">
                                  <UserIcon className={`w-4 h-4 mr-2 mt-0.5 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                  <div className="flex-1 min-w-0">
                                    <div className="truncate">
                                      {order.customerName || "N/A"}
                                    </div>
                                    {order.customerOrganizationName && (
                                      <div className={`text-xs ${getThemeClasses('text-secondary')} truncate`}>
                                        {order.customerOrganizationName}
                                        {order.customerDivisionName && ` - ${order.customerDivisionName}`}
                                      </div>
                                    )}
                                  </div>
                                </div>
                                <div className="flex items-center">
                                  <CurrencyDollarIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                  <span className="truncate">
                                    {order.totalAmount ? `$${parseFloat(order.totalAmount).toFixed(2)}` : "N/A"}
                                  </span>
                                </div>
                                {order.eventStartDateTime && (
                                  <div className="flex items-center">
                                    <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                    <span className="truncate text-sm">
                                      {formatDateTime(order.eventStartDateTime)}
                                    </span>
                                  </div>
                                )}
                              </div>

                              <ViewButton
                                basePath="/admin/event-order"
                                itemId={order.id}
                                text="View Order"
                                fullWidth={true}
                              />
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* Pagination */}
                      {(hasNextPage || currentPage > 1) && (
                        <div className={`mt-8 flex items-center justify-between border-t ${getThemeClasses('border-secondary')} pt-6`}>
                          <div className="flex-1 flex justify-between sm:hidden">
                            <Button
                              variant="secondary"
                              disabled={currentPage === 1}
                              onClick={() => handlePageChange(currentPage - 1)}
                            >
                              Previous
                            </Button>
                            <Button
                              variant="secondary"
                              disabled={!hasNextPage}
                              onClick={() => handlePageChange(currentPage + 1)}
                            >
                              Next
                            </Button>
                          </div>
                          <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                            <div>
                              <p className={`text-sm ${getThemeClasses('text-secondary')}`}>
                                Showing{" "}
                                <span className="font-medium">{eventOrders.length}</span>{" "}
                                results
                                {totalCount > 0 && (
                                  <>
                                    {" "}
                                    of <span className="font-medium">{totalCount}</span>{" "}
                                    total
                                  </>
                                )}
                              </p>
                            </div>
                            <div>
                              <nav
                                className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px"
                                aria-label="Pagination"
                              >
                                <Button
                                  variant="secondary"
                                  disabled={currentPage === 1}
                                  onClick={() => handlePageChange(currentPage - 1)}
                                >
                                  Previous
                                </Button>
                                <span className={`relative inline-flex items-center px-5 py-3 border-t border-b ${getThemeClasses('border-secondary')} ${getThemeClasses('badge-secondary')} text-sm font-medium`}>
                                  Page {currentPage}
                                </span>
                                <Button
                                  variant="secondary"
                                  disabled={!hasNextPage}
                                  onClick={() => handlePageChange(currentPage + 1)}
                                >
                                  Next
                                </Button>
                              </nav>
                            </div>
                          </div>
                        </div>
                      )}
                    </>
                  ) : (
                    /* Empty State */
                    <div className="text-center py-12">
                      <div className="mx-auto w-fit mb-4">
                        <DetailPageIcon icon={TicketIcon} size="xl" />
                      </div>
                      <h3 className={`mt-2 text-lg font-semibold ${getThemeClasses('text-primary')}`}>
                        No Event Orders Found
                      </h3>
                      <p className={`mt-1 text-sm ${getThemeClasses('text-secondary')}`}>
                        {searchTerm || statusFilter || selectedEventId || selectedCustomerId
                          ? "No event orders match your current filters. Try adjusting your search criteria."
                          : "No event orders have been added yet."}
                      </p>
                      <div className="mt-6 flex justify-center gap-3">
                        {(searchTerm || statusFilter || selectedEventId || selectedCustomerId) && (
                          <Button variant="secondary" onClick={() => {
                            setSearchTerm("");
                            setTempSearchTerm("");
                            setStatusFilter("");
                            setSelectedEventId("");
                            setSelectedCustomerId("");
                            setEventStartDateFrom("");
                            setEventStartDateTo("");
                            setCurrentPage(1);
                          }}>
                            Clear Filters
                          </Button>
                        )}
                        <Button
                          variant="success"
                          onClick={() => navigate("/admin/event-orders/add/step-1-search")}
                          icon={PlusIcon}
                        >
                          Create First Order
                        </Button>
                      </div>
                    </div>
                  )}
                </div>

              </div>
            </div>

            <style jsx>{`
              @keyframes blob {
                0% {
                  transform: translate(0px, 0px) scale(1);
                }
                33% {
                  transform: translate(30px, -50px) scale(1.1);
                }
                66% {
                  transform: translate(-20px, 20px) scale(0.9);
                }
                100% {
                  transform: translate(0px, 0px) scale(1);
                }
              }
              .animate-blob {
                animation: blob 7s infinite;
              }
              .animation-delay-2000 {
                animation-delay: 2s;
              }
              .animation-delay-4000 {
                animation-delay: 4s;
              }
            `}</style>
          </div>
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteModal && (
        <Modal
          isOpen={showDeleteModal}
          onClose={() => setShowDeleteModal(false)}
          title="Delete Event Order"
          size="md"
        >
          <div className="p-6">
            <div className="flex items-center mb-4">
              <ExclamationTriangleIcon className="w-8 h-8 text-red-600 mr-3 flex-shrink-0" />
              <div>
                <h3 className="text-lg font-medium text-gray-900">
                  Confirm Deletion
                </h3>
                <p className="text-sm text-gray-500 mt-1">
                  This action cannot be undone.
                </p>
              </div>
            </div>

            {eventOrderToDelete && (
              <div className="bg-gray-50 rounded-lg p-4 mb-4">
                <p className="text-sm text-gray-700">
                  <strong>Order:</strong> #{eventOrderToDelete.publicId || eventOrderToDelete.id}
                </p>
                <p className="text-sm text-gray-700 mt-1">
                  <strong>Event:</strong> {eventOrderToDelete.eventName || "N/A"}
                </p>
                <p className="text-sm text-gray-700 mt-1">
                  <strong>Customer:</strong> {eventOrderToDelete.customerName || "N/A"}
                </p>
              </div>
            )}

            <div className="flex justify-end space-x-3">
              <Button
                variant="secondary"
                onClick={() => setShowDeleteModal(false)}
                disabled={isLoading}
              >
                Cancel
              </Button>
              <Button
                variant="danger"
                onClick={handleDelete}
                disabled={isLoading}
                loading={isLoading}
              >
                Delete Order
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
}

export default AdminEventOrderListPage;
