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

import React, { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
  CalendarDaysIcon,
  ChevronLeftIcon,
  ArrowPathIcon,
  ClockIcon,
  ArchiveBoxIcon,
  ShoppingCartIcon,
  HomeIcon,
  ArrowRightIcon,
  InformationCircleIcon,
  EllipsisHorizontalIcon,
  DocumentTextIcon,
} from "@heroicons/react/24/outline";
import {
  useEventManager,
  useEventContractManager,
} from "../../../../../../../services/Services";
import { DetailLiteView, useUIXTheme } from "../../../../../../../components/UIX";
import { EVENT_TYPE_CONFERENCE } from "../../../../../../../constants/Event";
import { EVENT_CONTRACT_STATUS_ACTIVE, EVENT_CONTRACT_STATUS_ARCHIVED } from "../../../../../../../constants/EventContract";

// EventContract status mappings (matching backend EventContract)
const EVENT_CONTRACT_STATUS_OPTIONS = {
  [EVENT_CONTRACT_STATUS_ACTIVE]: { label: "Active", themeKey: "text-success" },
  [EVENT_CONTRACT_STATUS_ARCHIVED]: { label: "Archived", themeKey: "text-muted" },
};

function AdminConferenceDetailEventContractListPage() {
  const { eventId } = useParams();
  const navigate = useNavigate();
  const eventManager = useEventManager();
  const eventContractManager = useEventContractManager();
  const { getThemeClasses } = useUIXTheme();

  // Component states
  const [errors, setErrors] = useState({});
  const [isFetching, setFetching] = useState(false);
  const [isRefreshing, setRefreshing] = useState(false);
  const [event, setEvent] = useState(null);
  const [eventContractList, setEventContractList] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [lastFetchTime, setLastFetchTime] = useState(null);

  // Pagination state
  const [pageSize] = useState(50);
  const [sortByValue] = useState("created_at,DESC");
  const [status] = useState(0);

  // Use refs to track the latest filter values
  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 event contract list
  const fetchEventContractList = useCallback(async () => {
    const currentFilters = filtersRef.current;

    console.log("🔄 fetchEventContractList called with filters:", currentFilters);

    setFetching(true);
    setErrors({});

    eventContractManager.clearEventContractsCache();

    try {
      // Build filters map
      const filtersMap = new Map();
      filtersMap.set("page_size", currentFilters.pageSize.toString());
      filtersMap.set("event_id", eventId);

      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());
      }

      console.log("🌐 Making API call with filters:", Array.from(filtersMap.entries()));

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

      console.log("✅ API response received:", {
        resultsCount: data.results?.length,
        totalCount: data.count,
      });

      setEventContractList(data.results || []);
      setTotalCount(data.count || 0);
      setLastFetchTime(new Date());
    } catch (error) {
      console.error("❌ Failed to fetch event contract list:", error);
      setErrors(error);
    } finally {
      setFetching(false);
      setRefreshing(false);
    }
  }, [eventId, eventContractManager, onUnauthorized]);

  // Fetch event details
  const fetchEvent = useCallback(async () => {
    if (!eventId) return;

    setFetching(true);
    setErrors({});

    try {
      const eventData = await eventManager.getEventDetail(eventId, onUnauthorized);

      // Verify this is a conference event
      if (eventData.type !== EVENT_TYPE_CONFERENCE) {
        setErrors({ message: "This event is not a conference event" });
        return;
      }

      setEvent(eventData);
    } catch (err) {
      setErrors({ message: "Failed to load conference details. Please try again." });
    } finally {
      setFetching(false);
    }
  }, [eventId, eventManager, onUnauthorized]);

  // Initial load
  useEffect(() => {
    window.scrollTo(0, 0);
    fetchEvent();
  }, [fetchEvent]);

  // Fetch event contracts after event is loaded
  useEffect(() => {
    if (event?.id) {
      fetchEventContractList();
    }
  }, [event?.id, fetchEventContractList]);

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

  // Configure breadcrumb items
  const breadcrumbItems = useMemo(() => [
    {
      label: 'Dashboard',
      to: '/admin/dashboard',
      icon: HomeIcon,
      hideOnMobile: false,
      mobileLabel: 'Dash'
    },
    {
      label: 'Conferences',
      to: '/admin/events/conferences',
      icon: CalendarDaysIcon
    },
    {
      label: 'Event Contracts',
      icon: DocumentTextIcon,
      isActive: true
    }
  ], []);

  const headerConfig = useMemo(() => ({
    title: 'Conference - Event Contracts',
    icon: CalendarDaysIcon,
    loadingText: 'Loading conference event contracts...',
    notFoundTitle: 'Conference Event Not Found',
    notFoundMessage: "The conference event you're looking for doesn't exist or you don't have permission to view it.",
    notFoundAction: {
      label: 'Back to Conferences',
      icon: ChevronLeftIcon,
      onClick: () => navigate('/admin/events/conferences')
    }
  }), [navigate]);

  const actionButtons = useMemo(() => [
    {
      variant: "outline",
      onClick: () => navigate('/admin/events/conferences'),
      icon: ChevronLeftIcon,
      label: "Back"
    }
  ], [navigate]);

  const tabs = useMemo(() => {
    if (!eventId) return [];

    return [
      {
        label: "Summary",
        to: `/admin/events/conference/${eventId}`
      },
      {
        label: "Details",
        to: `/admin/events/conference/${eventId}/full`
      },
      {
        label: "Event Orders",
        to: `/admin/events/conference/${eventId}/event-orders`
      },
      {
        label: "Event Contracts",
        isActive: true
      },
      {
        label: "Comments",
        to: `/admin/events/conference/${eventId}/comments`
      },
      {
        label: "Attachments",
        to: `/admin/events/conference/${eventId}/attachments`
      },
      {
        label: "More",
        to: `/admin/events/conference/${eventId}/more`,
        icon: EllipsisHorizontalIcon
      }
    ];
  }, [eventId]);

  // Create field sections for the event contracts list
  const fieldSections = useMemo(() => {
    const sections = [
      {
        column: 'primary',
        className: 'mb-6',
        component: (
          <div>
            <div className="flex justify-between items-center mb-4">
              <h2 className={`text-xl sm:text-2xl font-bold ${getThemeClasses('text-primary')}`}>
                Event Contracts for {event?.eventName || "Loading..."}
              </h2>
              <button
                onClick={handleRefresh}
                disabled={isRefreshing || isFetching}
                className={`inline-flex items-center px-4 py-2 border rounded-lg text-sm font-medium transition-colors ${
                  isRefreshing || isFetching
                    ? 'opacity-50 cursor-not-allowed'
                    : getThemeClasses('hover-bg-muted')
                } ${getThemeClasses('border-border')} ${getThemeClasses('text-secondary')}`}
              >
                <ArrowPathIcon
                  className={`w-4 h-4 mr-2 ${isRefreshing || isFetching ? "animate-spin" : ""}`}
                />
                {isRefreshing ? "Refreshing..." : "Refresh"}
              </button>
            </div>

            {lastFetchTime && (
              <div className={`text-sm mb-4 flex items-center ${getThemeClasses('text-muted')}`}>
                <ClockIcon className="w-4 h-4 mr-1" />
                Last updated {Math.floor((new Date() - lastFetchTime) / 1000)} seconds ago
              </div>
            )}

            <div className={`mb-4 ${getThemeClasses('text-muted')}`}>
              Showing{" "}
              <strong className={getThemeClasses('text-primary')}>
                {eventContractList.length}
              </strong>{" "}
              event contracts
              {totalCount > 0 && ` (Total: ${totalCount})`}
            </div>

            {/* Event Contracts List */}
            {isFetching ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <div className={`animate-spin rounded-full h-10 w-10 border-b-2 mx-auto ${getThemeClasses('border-primary')}`}></div>
                  <p className={`mt-4 ${getThemeClasses('text-muted')}`}>
                    Loading event contracts...
                  </p>
                </div>
              </div>
            ) : eventContractList && eventContractList.length > 0 ? (
              <div className="space-y-3">
                {eventContractList.map((eventContract, index) => (
                  <div
                    key={eventContract.id || index}
                    className={`rounded-lg border p-4 ${getThemeClasses('bg-card')} ${getThemeClasses('border-border')}`}
                  >
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Contract #:</strong>
                        <div className={`font-mono text-sm ${getThemeClasses('text-primary')}`}>
                          #{eventContract.publicId}
                        </div>
                      </div>
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Facilitator:</strong>
                        <div className={`font-medium ${getThemeClasses('text-primary')}`}>
                          {eventContract.facilitatorName || "N/A"}
                        </div>
                      </div>
                      <div>
                        <strong className={getThemeClasses('text-secondary')}>Status:</strong>
                        <div
                          className={
                            getThemeClasses(EVENT_CONTRACT_STATUS_OPTIONS[eventContract.status]?.themeKey || "text-muted")
                          }
                        >
                          {EVENT_CONTRACT_STATUS_OPTIONS[eventContract.status]?.label || "Unknown"}
                        </div>
                      </div>
                      <div className="flex justify-end items-center">
                        <Link
                          to={`/admin/event-contract/${eventContract.id}`}
                          className={`inline-flex items-center font-medium ${getThemeClasses("link-primary")}`}
                        >
                          View Contract
                          <ArrowRightIcon className="w-3 h-3 ml-1" />
                        </Link>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className={`text-center py-16 rounded-lg ${getThemeClasses('bg-card')}`}>
                <DocumentTextIcon className={`w-12 h-12 mx-auto mb-4 ${getThemeClasses('text-muted')}`} />
                <h3 className={`text-lg font-medium mb-2 ${getThemeClasses('text-primary')}`}>
                  No Event Contracts Found
                </h3>
                <p className={getThemeClasses('text-muted')}>
                  This conference event does not have any contracts yet.
                </p>
              </div>
            )}
          </div>
        )
      }
    ];

    return sections;
  }, [
    event,
    eventContractList,
    totalCount,
    lastFetchTime,
    isFetching,
    isRefreshing,
    handleRefresh,
    getThemeClasses
  ]);

  const alerts = useMemo(() => ({
    archived: {
      message: 'This conference event is archived',
      icon: ArchiveBoxIcon
    }
  }), []);

  return (
    <DetailLiteView
      entityData={event}
      breadcrumbItems={breadcrumbItems}
      headerConfig={headerConfig}
      fieldSections={fieldSections}
      actionButtons={actionButtons}
      tabs={tabs}
      alerts={alerts}
      onUnauthorized={onUnauthorized}
      isLoading={isFetching && !event}
      error={errors?.message}
      onErrorClose={() => setErrors({})}
    />
  );
}

export default AdminConferenceDetailEventContractListPage;
