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

import React, { useState, useEffect, useCallback, useRef } from "react";
import { Link, useNavigate, useLocation } from "react-router";
import {
  useEventContractManager,
  useEventManager,
  useFacilitatorManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  EVENT_CONTRACT_STATUS_OPTIONS,
  getEventContractStatusLabel,
  getEventContractStatusVariant,
} from "../../../../constants/EventContract";
import {
  EVENT_TYPE_CONFERENCE,
  EVENT_TYPE_ONSITE,
  EVENT_TYPE_OFFSITE,
  EVENT_TYPE_VIRTUAL,
} from "../../../../constants/Event";
import {
  UIXThemeProvider,
  useUIXTheme,
  DataList,
  Breadcrumb,
  Badge,
  Button,
  Modal,
  Alert,
  DetailPageIcon,
  ViewButton,
  Card,
} from "../../../../components/UIX";
import {
  ClipboardDocumentListIcon,
  PlusIcon,
  EyeIcon,
  PencilSquareIcon,
  TrashIcon,
  HashtagIcon,
  CalendarIcon,
  UserIcon,
  CurrencyDollarIcon,
  DocumentTextIcon,
  XMarkIcon,
  ExclamationTriangleIcon,
  HomeIcon,
  ArrowLeftIcon,
  Squares2X2Icon,
  TableCellsIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  ClockIcon,
} from "@heroicons/react/24/outline";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

// Constants
const DEFAULT_PAGE = 1;
const DEFAULT_PAGE_SIZE = 25;
const PAGE_SIZE_OPTIONS = [
  { value: "10", label: "10 per page" },
  { value: "25", label: "25 per page" },
  { value: "50", label: "50 per page" },
  { value: "100", label: "100 per page" },
];

const EVENT_CONTRACT_SORT_OPTIONS = [
  { value: "created_at,DESC", label: "Newest First" },
  { value: "created_at,ASC", label: "Oldest First" },
  { value: "event_name,ASC", label: "Event Name (A-Z)" },
  { value: "event_name,DESC", label: "Event Name (Z-A)" },
  { value: "status,ASC", label: "Status (A-Z)" },
  { value: "status,DESC", label: "Status (Z-A)" },
];

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

// Helper function to get event type label
const getEventTypeLabel = (eventType) => {
  // Convert to number in case it comes as a string
  const typeNum =
    typeof eventType === "string" ? parseInt(eventType, 10) : eventType;

  switch (typeNum) {
    case EVENT_TYPE_CONFERENCE:
      return "Conference";
    case EVENT_TYPE_ONSITE:
      return "Onsite";
    case EVENT_TYPE_OFFSITE:
      return "Offsite";
    case EVENT_TYPE_VIRTUAL:
      return "Virtual";
    default:
      return "";
  }
};

function AdminEventContractListPage() {
  return (
    <UIXThemeProvider>
      <AdminEventContractListPageContent />
    </UIXThemeProvider>
  );
}

function AdminEventContractListPageContent() {
  const { getThemeClasses } = useUIXTheme();
  const eventContractManager = useEventContractManager();
  const eventManager = useEventManager();
  const facilitatorManager = useFacilitatorManager();
  const authManager = useAuthManager();
  const navigate = useNavigate();
  const location = useLocation();
  const isLoadingRef = useRef(false);

  // Main state
  const [eventContracts, setEventContracts] = 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);

  // Extended filters
  const [selectedEventId, setSelectedEventId] = useState("");
  const [selectedFacilitatorId, setSelectedFacilitatorId] = useState("");
  const [eventStartDateFrom, setEventStartDateFrom] = useState("");
  const [eventStartDateTo, setEventStartDateTo] = useState("");

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

  // Delete confirmation modal
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [eventContractToDelete, setEventContractToDelete] = useState(null);

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

  // Load select options for events and facilitators
  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 facilitators for filter dropdown
      const facilitatorsResponse = await facilitatorManager.getFacilitators(
        { limit: 100, status: "1" }, // Active facilitators
        onUnauthorized,
        false,
      );
      if (facilitatorsResponse?.results) {
        setFacilitators(facilitatorsResponse.results);
      }
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to load select options:", err);
      }
    } finally {
      setLoadingSelectOptions(false);
    }
  }, [eventManager, facilitatorManager]);

  // Fetch event contracts using the manager
  const fetchEventContracts = useCallback(
    async (params = {}) => {
      // Prevent double loading
      if (isLoadingRef.current && !params.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,
          ...params,
        };

        // Add optional filters
        if (statusFilter) queryParams.status = statusFilter;
        if (selectedEventId) queryParams.eventId = selectedEventId;
        if (selectedFacilitatorId)
          queryParams.facilitatorId = selectedFacilitatorId;
        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 eventContractManager.getEventContracts(
          queryParams,
          onUnauthorized,
          params.forceRefresh || false,
        );

        if (response?.results) {
          setEventContracts(response.results);
          setTotalCount(response.count || 0);
          setHasNextPage(response.hasNextPage || false);
        } else {
          setEventContracts([]);
          setTotalCount(0);
          setHasNextPage(false);
        }
      } catch (err) {
        if (process.env.NODE_ENV === 'development') {
          console.error("Failed to fetch event contracts:", err);
        }
        setErrors({
          fetch: "Failed to load event contracts. Please try again.",
        });
        setEventContracts([]);
        setTotalCount(0);
        setHasNextPage(false);
      } finally {
        setIsLoading(false);
        isLoadingRef.current = false;
      }
    },
    [
      eventContractManager,
      currentPage,
      pageSize,
      searchTerm,
      sortBy,
      statusFilter,
      selectedEventId,
      selectedFacilitatorId,
      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
  const handleDelete = useCallback(async () => {
    if (!eventContractToDelete) return;

    try {
      setIsLoading(true);
      await eventContractManager.deleteEventContract(
        eventContractToDelete.id,
        onUnauthorized,
      );
      setSuccessMessage("Event contract deleted successfully");
      setShowDeleteModal(false);
      setEventContractToDelete(null);
      fetchEventContracts({ forceRefresh: true });
    } catch (err) {
      if (process.env.NODE_ENV === 'development') {
        console.error("Failed to delete event contract:", err);
      }
      setErrors({
        delete: "Failed to delete event contract. Please try again.",
      });
    } finally {
      setIsLoading(false);
    }
  }, [eventContractToDelete, eventContractManager, fetchEventContracts]);

  // Initial load - load select options AND fetch data
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login?unauthorized=true");
      return;
    }
    loadSelectOptions();
    fetchEventContracts({ forceRefresh: true });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Only run once on mount

  // Fetch data when dependencies change (skip initial mount since we handle that above)
  useEffect(() => {
    // Skip if this is the initial render (fetchEventContracts already called above)
    if (isLoadingRef.current) {
      return;
    }

    if (authManager.isAuthenticated()) {
      fetchEventContracts();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    currentPage,
    pageSize,
    searchTerm,
    sortBy,
    statusFilter,
    selectedEventId,
    selectedFacilitatorId,
    eventStartDateFrom,
    eventStartDateTo,
  ]); // Only re-fetch when filter/pagination params change

  // Column configuration for DataList
  const columns = [
    {
      key: "eventName",
      header: "Event",
      sortable: true,
      render: (value, eventContract) => (
        <div className="flex items-center">
          <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
          <div className="min-w-0">
            <div className={`text-sm font-medium ${getThemeClasses('text-primary')} truncate`}>
              {value || "N/A"}
            </div>
            {eventContract.eventDate && (
              <div className={`text-xs ${getThemeClasses('text-muted')}`}>
                {formatDateForDisplay(eventContract.eventDate)}
              </div>
            )}
          </div>
        </div>
      ),
    },
    {
      key: "facilitatorName",
      header: "Facilitator",
      sortable: true,
      render: (value, eventContract) => {
        const facilitatorName =
          value ||
          (eventContract.facilitatorFirstName &&
          eventContract.facilitatorLastName
            ? `${eventContract.facilitatorFirstName} ${eventContract.facilitatorLastName}`.trim()
            : null);

        return (
          <div className="flex items-center">
            <UserIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
            <span className={`text-sm ${getThemeClasses('text-primary')} truncate`}>
              {facilitatorName || "-"}
            </span>
          </div>
        );
      },
    },
    {
      key: "estimatedContractHours",
      header: "Hours",
      sortable: true,
      render: (value) => (
        <div className="flex items-center">
          <ClockIcon className={`w-4 h-4 mr-1 ${getThemeClasses('text-muted')} flex-shrink-0`} />
          <span className={`text-sm font-medium ${getThemeClasses('text-primary')}`}>
            {value ? `${value}` : "-"}
          </span>
        </div>
      ),
    },
    {
      key: "actions",
      header: "Actions",
      sortable: false,
      render: (_, eventContract) => (
        <ViewButton
          to={`/admin/event-contract/${eventContract.id}`}
          text="View"
        />
      ),
    },
  ];

  // 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: "selectedFacilitatorId",
      label: "Facilitator",
      value: selectedFacilitatorId,
      onChange: (value) => {
        setSelectedFacilitatorId(value);
        handleFilterChange();
      },
      options: [
        { value: "", label: "All Facilitators" },
        ...facilitators.map((facilitator) => ({
          value: facilitator.id,
          label:
            facilitator.name ||
            `${facilitator.firstName} ${facilitator.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 Contracts",
            icon: ClipboardDocumentListIcon,
            isActive: true,
          },
        ]}
      />

      {/* Conditional Rendering: DataList for table view, Custom Grid for card view */}
      {viewType === VIEW_TYPE_TABULAR ? (
        <DataList
          data={eventContracts}
          columns={columns}
          isLoading={isLoading}
          errors={errors}
          successMessage={successMessage}
          onSuccessMessageClose={() => setSuccessMessage("")}
          searchFilter={{
            searchTerm,
            tempSearchTerm,
            onSearchTermChange: setTempSearchTerm,
            onSearchSubmit: handleSearch,
            placeholder: "Search by contract #, event name, facilitator...",
            basicFilters: [
              {
                type: "select",
                key: "status",
                label: "Status",
                value: statusFilter,
                onChange: (value) => {
                  setStatusFilter(value);
                  handleFilterChange();
                },
                options: EVENT_CONTRACT_STATUS_OPTIONS,
              },
              {
                type: "select",
                key: "sortBy",
                label: "Sort By",
                value: sortBy,
                onChange: handleSortChange,
                options: EVENT_CONTRACT_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: ClipboardDocumentListIcon,
            title: "No Event Contracts Found",
            description:
              searchTerm ||
              statusFilter ||
              selectedEventId ||
              selectedFacilitatorId
                ? "No event contracts match your current filters. Try adjusting your search criteria."
                : "No event contracts have been added yet.",
            actionLabel: "Create Contract",
            onActionClick: () =>
              navigate("/admin/event-contracts/add/step-1-search"),
            isCreateAction: true,
          }}
          header={{
            icon: ClipboardDocumentListIcon,
            title: "Event Contract Management",
            showHeader: true,
            subtitle:
              "Manage contracts for events, facilitator agreements, and payment terms",
            decorativeIcon: <DetailPageIcon icon={ClipboardDocumentListIcon} />,
            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-contracts/search")}
                icon={ArrowLeftIcon}
              >
                Advanced Search
              </Button>,
              <Button
                key="add"
                variant="success"
                size="lg"
                onClick={() =>
                  navigate("/admin/event-contracts/add/step-1-search")
                }
                icon={PlusIcon}
              >
                Create Contract
              </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")}`}
                        >
                          <ClipboardDocumentListIcon 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 Contract 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-contracts/search")
                        }
                        icon={ArrowLeftIcon}
                      >
                        Advanced Search
                      </Button>
                      <Button
                        variant="success"
                        size="lg"
                        onClick={() =>
                          navigate("/admin/event-contracts/add/step-1-search")
                        }
                        icon={PlusIcon}
                      >
                        Create Contract
                      </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>
                  ) : eventContracts?.length > 0 ? (
                    <>
                      {/* Results count */}
                      <div
                        className={`mb-6 text-sm ${getThemeClasses("text-secondary")}`}
                      >
                        Showing <strong>{eventContracts.length}</strong>{" "}
                        contracts
                        {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">
                        {eventContracts.map((contract) => (
                          <div
                            key={contract.id}
                            className={`bg-white border ${getThemeClasses("card-border")} rounded-lg shadow-sm hover:shadow-lg transition-shadow flex flex-col h-full`}
                          >
                            <div className="p-6 flex-1 flex flex-col">
                              <div className="flex-1">
                                <div className="mb-4">
                                  <h3
                                    className={`text-lg font-semibold ${getThemeClasses("text-primary")} flex items-start`}
                                  >
                                    <CalendarIcon
                                      className={`w-5 h-5 mr-2 flex-shrink-0 mt-0.5 ${getThemeClasses("text-muted")}`}
                                    />
                                    <span>{contract.eventName || "N/A"}</span>
                                  </h3>

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

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

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

                                  {/* Event Date and Time */}
                                  {(contract.eventStartDateTime ||
                                    contract.eventEndDateTime) && (
                                    <div className={`mt-3 text-sm ${getThemeClasses('text-secondary')}`}>
                                      {contract.eventStartDateTime && (
                                        <div className="flex items-center mb-1">
                                          <CalendarIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                          <span>
                                            {new Date(
                                              contract.eventStartDateTime,
                                            ).toLocaleDateString("en-US", {
                                              year: "numeric",
                                              month: "short",
                                              day: "numeric",
                                            })}{" "}
                                            at{" "}
                                            {new Date(
                                              contract.eventStartDateTime,
                                            ).toLocaleTimeString("en-US", {
                                              hour: "numeric",
                                              minute: "2-digit",
                                              hour12: true,
                                            })}
                                          </span>
                                        </div>
                                      )}
                                      {contract.eventEndDateTime && (
                                        <div className="flex items-center">
                                          <ClockIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')} flex-shrink-0`} />
                                          <span>
                                            Ends at{" "}
                                            {new Date(
                                              contract.eventEndDateTime,
                                            ).toLocaleTimeString("en-US", {
                                              hour: "numeric",
                                              minute: "2-digit",
                                              hour12: true,
                                            })}
                                          </span>
                                        </div>
                                      )}
                                    </div>
                                  )}
                                </div>

                                <div
                                  className={`space-y-2 text-base ${getThemeClasses("text-primary")} mb-4`}
                                >
                                  <div className="flex items-center">
                                    <UserIcon
                                      className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")} flex-shrink-0`}
                                    />
                                    <span className="truncate">
                                      {contract.facilitatorName ||
                                        (contract.facilitatorFirstName &&
                                        contract.facilitatorLastName
                                          ? `${contract.facilitatorFirstName} ${contract.facilitatorLastName}`.trim()
                                          : "-")}
                                    </span>
                                  </div>
                                  <div className="flex items-center">
                                    <ClockIcon
                                      className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")} flex-shrink-0`}
                                    />
                                    <span className="truncate">
                                      {contract.estimatedContractHours || "-"}
                                    </span>
                                  </div>
                                  {contract.eventDate && (
                                    <div className="flex items-center">
                                      <CalendarIcon
                                        className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")} flex-shrink-0`}
                                      />
                                      <span className="truncate text-sm">
                                        {formatDateForDisplay(
                                          contract.eventDate,
                                        )}
                                      </span>
                                    </div>
                                  )}
                                </div>
                              </div>

                              <ViewButton
                                to={`/admin/event-contract/${contract.id}`}
                                text="View Contract"
                                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">
                                  {eventContracts.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={ClipboardDocumentListIcon}
                          size="xl"
                        />
                      </div>
                      <h3
                        className={`mt-2 text-lg font-semibold ${getThemeClasses("text-primary")}`}
                      >
                        No Event Contracts Found
                      </h3>
                      <p
                        className={`mt-1 text-sm ${getThemeClasses("text-secondary")}`}
                      >
                        {searchTerm ||
                        statusFilter ||
                        selectedEventId ||
                        selectedFacilitatorId
                          ? "No event contracts match your current filters. Try adjusting your search criteria."
                          : "No event contracts have been added yet."}
                      </p>
                      <div className="mt-6 flex justify-center gap-3">
                        {(searchTerm ||
                          statusFilter ||
                          selectedEventId ||
                          selectedFacilitatorId) && (
                          <Button
                            variant="secondary"
                            onClick={() => {
                              setSearchTerm("");
                              setTempSearchTerm("");
                              setStatusFilter("");
                              setSelectedEventId("");
                              setSelectedFacilitatorId("");
                              setEventStartDateFrom("");
                              setEventStartDateTo("");
                              setCurrentPage(1);
                            }}
                          >
                            Clear Filters
                          </Button>
                        )}
                        <Button
                          variant="success"
                          onClick={() =>
                            navigate("/admin/event-contracts/add/step-1-search")
                          }
                          icon={PlusIcon}
                        >
                          Create First Contract
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            <style>{`
              @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 Contract"
          size="md"
        >
          <div className="p-6">
            <div className="flex items-center mb-4">
              <ExclamationTriangleIcon className={`w-8 h-8 ${getThemeClasses('text-danger')} mr-3 flex-shrink-0`} />
              <div>
                <h3 className={`text-lg font-medium ${getThemeClasses('text-primary')}`}>
                  Confirm Deletion
                </h3>
                <p className={`text-sm ${getThemeClasses('text-muted')} mt-1`}>
                  This action cannot be undone.
                </p>
              </div>
            </div>

            {eventContractToDelete && (
              <div className={`${getThemeClasses('bg-muted')} rounded-lg p-4 mb-4`}>
                <p className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  <strong>Contract:</strong> #
                  {eventContractToDelete.publicId || eventContractToDelete.id}
                </p>
                <p className={`text-sm ${getThemeClasses('text-secondary')} mt-1`}>
                  <strong>Event:</strong>{" "}
                  {eventContractToDelete.eventName || "N/A"}
                </p>
                <p className={`text-sm ${getThemeClasses('text-secondary')} mt-1`}>
                  <strong>Facilitator:</strong>{" "}
                  {eventContractToDelete.facilitatorName ||
                    `${eventContractToDelete.facilitatorFirstName} ${eventContractToDelete.facilitatorLastName}` ||
                    "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 Contract
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
}

export default AdminEventContractListPage;
