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

import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  ChartBarIcon,
  UserGroupIcon,
  InformationCircleIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  EllipsisHorizontalIcon,
  ArrowRightIcon,
  BuildingOfficeIcon,
  ArrowTopRightOnSquareIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import {
  useFacilitatorManager,
  useEventContractManager,
} from "../../../../../../services/Services";
import { DateTime } from "luxon";
import { formatDateForDisplay } from "../../../../../../services/Helpers/DateFormatter";
import {
  UIXThemeProvider,
  PageHeader,
  Breadcrumb,
  Tabs,
  Alert,
  Button,
  Select,
  Table,
  Badge,
  Spinner,
  useUIXTheme,
} from "../../../../../../components/UIX";

// Constants
const COMMERCIAL_FACILITATOR_TYPE_OF_ID = 3;
const RESIDENTIAL_FACILITATOR_TYPE_OF_ID = 2;

// EventContract status mappings
const EVENT_CONTRACT_STATUS_OPTIONS = {
  1: { label: "Active", variant: "success" },
  2: { label: "Archived", variant: "secondary" },
};

// Event type mappings
const EVENT_TYPE_OPTIONS = {
  0: { label: "-", icon: null },
  1: { label: "Conference", icon: BuildingOfficeIcon },
  2: { label: "Onsite", icon: UserGroupIcon },
  3: { label: "Offsite", icon: ChartBarIcon },
  4: { label: "Virtual", icon: ChartBarIcon },
};

function AdminFacilitatorDetailEventContractListPage() {
  const { aid } = useParams();
  const navigate = useNavigate();
  const facilitatorManager = useFacilitatorManager();
  const eventContractManager = useEventContractManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [isRefreshing, setRefreshing] = useState(false);
  const [facilitator, setFacilitator] = useState({});
  const [eventContractList, setEventContractList] = 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(50);

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

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

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

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

  // Fetch facilitator details
  const fetchFacilitatorDetail = useCallback(async () => {
    try {
      const data = await facilitatorManager.getFacilitatorDetail(
        aid,
        onUnauthorized,
      );
      setFacilitator(data);
    } catch (error) {
      setErrors(error);
    }
  }, [aid, facilitatorManager, onUnauthorized]);

  // Fetch eventContract list with force refresh option
  const fetchEventContractList = useCallback(
    async (cursor = "", isNavigatingBack = false) => {
      const currentFilters = filtersRef.current;

      setFetching(true);
      setErrors({});

      if (!isNavigatingBack) {
        eventContractManager.clearEventContractsCache();
      }

      try {
        const filtersMap = new Map();

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

        filtersMap.set("page_size", currentFilters.pageSize.toString());
        filtersMap.set("facilitator_id", aid);

        const sortArray = currentFilters.sortByValue.split(",");
        filtersMap.set("sort_field", sortArray[0]);
        filtersMap.set("sort_order", sortArray[1]);

        if (currentFilters.status !== 0) {
          filtersMap.set("status", currentFilters.status.toString());
        }

        const data = await eventContractManager.getEventContractsWithFiltersMap(
          filtersMap,
          onUnauthorized,
          true,
        );

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

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

        if (data.hasNextPage !== undefined) {
          setHasNextPage(data.hasNextPage);
        }

        if (!isNavigatingBack) {
          setCurrentCursor(cursor);
        }

        setLastFetchTime(new Date());
      } catch (error) {
        setErrors(error);
      } finally {
        setFetching(false);
        setRefreshing(false);
      }
    },
    [aid, eventContractManager, onUnauthorized],
  );

  // Immediate filter application function
  const applyFilters = useCallback(() => {
    setCursorHistory([]);
    setCurrentCursor("");
    setNextCursor("");
    setHasNextPage(false);
    eventContractManager.clearEventContractsCache();
    fetchEventContractList("");
  }, [fetchEventContractList, eventContractManager]);

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

  // Pagination handlers
  const handleNextPage = useCallback(() => {
    if (hasNextPage && nextCursor) {
      setCursorHistory((prev) => [...prev, currentCursor]);
      fetchEventContractList(nextCursor);
    }
  }, [hasNextPage, nextCursor, currentCursor, fetchEventContractList]);

  const handlePreviousPage = useCallback(() => {
    if (cursorHistory.length > 0) {
      const newHistory = [...cursorHistory];
      const previousCursor = newHistory.pop();
      setCursorHistory(newHistory);
      fetchEventContractList(previousCursor || "", true);
    }
  }, [cursorHistory, fetchEventContractList]);

  // Handle page size change
  const handlePageSizeChange = useCallback((value) => {
    const newPageSize = parseInt(value);
    setPageSize(newPageSize);
    setTimeout(() => applyFilters(), 0);
  }, [applyFilters]);

  // Handle sort change
  const handleSortChange = useCallback((value) => {
    setSortByValue(value);
    setTimeout(() => applyFilters(), 0);
  }, [applyFilters]);

  // Handle status filter change
  const handleStatusFilterChange = useCallback((value) => {
    setStatus(parseInt(value));
    setTimeout(() => applyFilters(), 0);
  }, [applyFilters]);

  // Format status helper with Badge
  const formatStatus = useCallback((statusValue) => {
    const statusOption = EVENT_CONTRACT_STATUS_OPTIONS[statusValue];
    if (!statusOption) return <span>Unknown ({statusValue})</span>;

    return (
      <Badge variant={statusOption.variant} size="sm">
        {statusOption.label}
      </Badge>
    );
  }, []);

  // 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]);

  // Initial load
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchFacilitatorDetail();
    eventContractManager.clearEventContractsCache();
  }, [aid, fetchFacilitatorDetail, eventContractManager]);

  // Initial data load
  useEffect(() => {
    if (aid) {
      fetchEventContractList("");
    }
  }, [aid, fetchEventContractList]);

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

  // Sort options - memoized to prevent recreation
  const sortOptions = useMemo(() => [
    { value: "created_at,DESC", label: "Created Date (Newest)" },
    { value: "created_at,ASC", label: "Created Date (Oldest)" },
    { value: "event_start_date_time,DESC", label: "Event Start Date (Newest)" },
    { value: "event_start_date_time,ASC", label: "Event Start Date (Oldest)" },
    { value: "event_name,ASC", label: "Event Name (A-Z)" },
    { value: "event_name,DESC", label: "Event Name (Z-A)" },
  ], []);

  // Status filter options - memoized to prevent recreation and map operation
  const statusFilterOptions = useMemo(() => [
    { value: "0", label: "All Statuses" },
    ...Object.entries(EVENT_CONTRACT_STATUS_OPTIONS).map(([value, option]) => ({
      value,
      label: option.label,
    })),
  ], []);

  // Tabs configuration - memoized to prevent recreation
  const tabs = useMemo(() => [
    {
      id: "summary",
      label: "Summary",
      to: `/admin/facilitator/${aid}`,
    },
    {
      id: "detail",
      label: "Full Details",
      to: `/admin/facilitator/${aid}/detail`,
    },
    {
      id: "event-contracts",
      label: "Event Contracts",
      to: `/admin/facilitator/${aid}/event-contracts`,
    },
    {
      id: "comments",
      label: "Comments",
      to: `/admin/facilitator/${aid}/comments`,
    },
    {
      id: "attachments",
      label: "Attachments",
      to: `/admin/facilitator/${aid}/attachments`,
    },
    {
      id: "more",
      label: "More",
      to: `/admin/facilitator/${aid}/more`,
      icon: EllipsisHorizontalIcon,
    },
  ], [aid]);

  // Table columns - memoized to prevent recreation of render functions
  const columns = useMemo(() => [
    {
      key: "publicId",
      header: "Contract #",
      render: (row) => <span className="font-mono">#{row.publicId}</span>,
    },
    {
      key: "eventName",
      header: "Event Name",
      render: (row) => (
        <div>
          <div className="font-medium">{row.eventName}</div>
          {row.eventDescription && (
            <div className={`text-xs ${getThemeClasses('text-muted')} truncate max-w-xs`}>
              {row.eventDescription}
            </div>
          )}
        </div>
      ),
    },
    {
      key: "eventType",
      header: "Event Type",
      render: (row) => formatEventType(row.eventType),
    },
    {
      key: "eventStartDateTime",
      header: "Start Date",
      render: (row) => formatDateForDisplay(row.eventStartDateTime),
    },
    {
      key: "eventEndDateTime",
      header: "End Date",
      render: (row) => formatDateForDisplay(row.eventEndDateTime),
    },
    {
      key: "status",
      header: "Status",
      render: (row) => formatStatus(row.status),
    },
    {
      key: "actions",
      header: "Actions",
      render: (row) => (
        <Link
          to={`/admin/event-contract/${row.id}`}
          className={`${getThemeClasses('link-primary')} inline-flex items-center`}
        >
          View
          <ArrowRightIcon className="w-3 h-3 ml-1" />
        </Link>
      ),
    },
  ], [formatEventType, formatStatus]); // getThemeClasses removed - captured in closure

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

  if (isFetching && !facilitator.id) {
    return (
      <UIXThemeProvider>
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
          <div className="flex items-center justify-center min-h-[400px]">
            <div className="text-center">
              <Spinner size="lg" />
              <p className={`mt-4 text-sm sm:text-base ${getThemeClasses('text-secondary')}`}>
                Loading facilitator event contracts...
              </p>
            </div>
          </div>
        </div>
      </UIXThemeProvider>
    );
  }

  return (
    <UIXThemeProvider>
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 sm:py-8">
        {/* Breadcrumb */}
        <Breadcrumb
          items={[
            { label: "Dashboard", href: "/admin/dashboard", icon: ChartBarIcon },
            { label: "Facilitators", href: "/admin/facilitators", icon: UserGroupIcon },
            { label: "Detail", icon: InformationCircleIcon },
          ]}
          className="mb-4 sm:mb-6"
        />

        {/* Page Header */}
        <PageHeader
          title="Facilitator"
          subtitle="View and manage event contracts"
          icon={UserGroupIcon}
          className="mb-4 sm:mb-6"
        />

        {/* Status Alerts */}
        {facilitator && facilitator.status === 2 && (
          <Alert
            type="info"
            message="This facilitator is archived"
            icon={ArchiveBoxIcon}
            className="mb-4"
          />
        )}

        {/* Error Display */}
        {errors && typeof errors === "object" && Object.keys(errors).length > 0 && (
          <Alert
            type="error"
            message={
              <div>
                <strong>Error:</strong>
                <ul className="mt-2 list-disc list-inside">
                  {Object.entries(errors).map(([key, value]) => (
                    <li key={key}>
                      {key}: {value}
                    </li>
                  ))}
                </ul>
              </div>
            }
            onClose={() => setErrors({})}
            className="mb-4"
          />
        )}

        {/* Main Content */}
        <div className={`bg-white shadow-sm rounded-lg ${getThemeClasses('card-border')}`}>
          {facilitator && facilitator.id ? (
            <>
              {/* Header with Title and Refresh Button */}
              <div className={`px-4 sm:px-6 py-4 sm:py-5 border-b ${getThemeClasses('border-secondary')}`}>
                <div className="flex justify-between items-center flex-wrap gap-3 sm:gap-4">
                  <div className="flex items-center gap-3 sm:gap-4">
                    <h2 className={`text-xl sm:text-2xl font-semibold ${getThemeClasses('text-primary')} flex items-center`}>
                      <InformationCircleIcon className="w-6 h-6 sm:w-7 sm:h-7 mr-2" />
                      Event Contracts
                    </h2>
                    {lastFetchTime && (
                      <span className={`text-xs sm:text-sm ${getThemeClasses('text-secondary')} flex items-center`}>
                        <ClockIcon className="w-3 h-3 sm:w-4 sm:h-4 mr-1" />
                        {formatLastFetchTime()}
                      </span>
                    )}
                  </div>
                  <Button
                    onClick={handleRefresh}
                    disabled={isRefreshing}
                    variant="outline"
                    icon={ArrowPathIcon}
                    iconClassName={isRefreshing ? "animate-spin" : ""}
                    size="md"
                  >
                    {isRefreshing ? "Refreshing..." : "Refresh"}
                  </Button>
                </div>
              </div>

              {/* Tab Navigation */}
              <div className={`px-4 sm:px-6 border-b ${getThemeClasses('border-secondary')}`}>
                <Tabs mode="routing" tabs={tabs} activeTabId="event-contracts" />
              </div>

              <div className="p-4 sm:p-6">
                {/* Filters Section */}
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3 sm:gap-4 mb-4 sm:mb-6">
                  <Select
                    label="Status Filter"
                    value={String(status)}
                    onChange={handleStatusFilterChange}
                    options={statusFilterOptions}
                  />

                  <Select
                    label="Sort By"
                    value={sortByValue}
                    onChange={handleSortChange}
                    options={sortOptions}
                  />

                  <Select
                    label="Items per page"
                    value={String(pageSize)}
                    onChange={handlePageSizeChange}
                    options={pageSizeOptions}
                  />
                </div>

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

                {/* EventContracts List */}
                {isFetching || isRefreshing ? (
                  <div className="flex items-center justify-center py-12">
                    <div className="text-center">
                      <Spinner size="md" />
                      <p className={`mt-4 ${getThemeClasses('text-secondary')}`}>
                        {isRefreshing ? "Refreshing event contracts..." : "Loading event contracts..."}
                      </p>
                    </div>
                  </div>
                ) : eventContractList &&
                  eventContractList.results &&
                  eventContractList.results.length > 0 ? (
                  <>
                    {/* EventContracts Table */}
                    <Table
                      data={eventContractList.results}
                      columns={columns}
                      emptyMessage="No event contracts found"
                    />

                    {/* Pagination Controls */}
                    {(hasPreviousPage || hasNextPage) && (
                      <div className={`flex justify-between items-center pt-4 sm:pt-6 border-t ${getThemeClasses('border-secondary')} mt-4 sm:mt-6`}>
                        <div className={`flex items-center text-xs sm:text-sm ${getThemeClasses('text-primary')}`}>
                          Page {currentPageNumber}
                          {totalCount > 0 && (
                            <span className={`ml-2 ${getThemeClasses('text-secondary')}`}>
                              (Total: {totalCount} event contracts)
                            </span>
                          )}
                        </div>
                        <div className="flex gap-2 sm:gap-3">
                          {hasPreviousPage && (
                            <Button
                              onClick={handlePreviousPage}
                              variant="outline"
                              icon={ChevronLeftIcon}
                              iconPosition="left"
                              size="sm"
                            >
                              Previous
                            </Button>
                          )}
                          {hasNextPage && (
                            <Button
                              onClick={handleNextPage}
                              variant="primary"
                              icon={ChevronRightIcon}
                              iconPosition="right"
                              size="sm"
                            >
                              Next
                            </Button>
                          )}
                        </div>
                      </div>
                    )}
                  </>
                ) : (
                  <div className={`text-center py-12 sm:py-16 ${getThemeClasses('bg-card')} rounded-lg border ${getThemeClasses('border-secondary')}`}>
                    <UserGroupIcon className={`w-10 h-10 sm:w-12 sm:h-12 ${getThemeClasses('text-muted')} mx-auto mb-3 sm:mb-4`} />
                    <h3 className={`text-base sm:text-lg font-medium ${getThemeClasses('text-primary')} mb-2`}>
                      No Event Contracts Found
                    </h3>
                    <p className={getThemeClasses('text-secondary')}>
                      {status !== 0
                        ? "No event contracts match the selected status filter."
                        : "This facilitator does not have any event contracts yet."}
                    </p>
                  </div>
                )}

                {/* Action Buttons */}
                <div className={`flex justify-start mt-6 sm:mt-8 pt-4 sm:pt-6 border-t ${getThemeClasses('border-secondary')}`}>
                  <Button
                    variant="outline"
                    icon={ChevronLeftIcon}
                    iconPosition="left"
                    onClick={() => navigate("/admin/facilitators")}
                  >
                    Back to Facilitators
                  </Button>
                </div>
              </div>
            </>
          ) : (
            !isFetching && (
              <div className="px-4 sm:px-6 py-12 sm:py-16 text-center">
                <div className={`inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 ${getThemeClasses('bg-card')} rounded-full mb-3 sm:mb-4 border ${getThemeClasses('border-secondary')}`}>
                  <UserGroupIcon className={`w-6 h-6 sm:w-8 sm:h-8 ${getThemeClasses('text-muted')}`} />
                </div>
                <h3 className={`text-base sm:text-lg font-medium ${getThemeClasses('text-primary')} mb-2`}>
                  Facilitator Not Found
                </h3>
                <p className={`${getThemeClasses('text-secondary')} mb-4 sm:mb-6 text-sm sm:text-base`}>
                  The facilitator you're looking for doesn't exist or you don't have permission to view it.
                </p>
                <Button
                  variant="primary"
                  icon={ChevronLeftIcon}
                  iconPosition="left"
                  onClick={() => navigate("/admin/facilitators")}
                >
                  Back to Facilitators
                </Button>
              </div>
            )
          )}
        </div>
      </div>
    </UIXThemeProvider>
  );
}

export default AdminFacilitatorDetailEventContractListPage;
