// File Path: monorepo/web/frontend/src/pages/Admin/EventContract/Search/ResultPage.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useEventContractManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  EyeIcon,
  DocumentTextIcon,
  CalendarIcon,
  BuildingOfficeIcon,
  UserGroupIcon,
  HomeIcon,
  PlusIcon,
} from "@heroicons/react/24/outline";
import {
  SearchResultsPage,
  ViewButton,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import {
  PAGE_SIZE_OPTIONS,
} from "../../../../constants/FieldOptions";
import {
  EVENT_CONTRACT_STATUS_FILTER_OPTIONS,
  EVENT_CONTRACT_TYPE_FILTER_OPTIONS,
  EVENT_CONTRACT_SECTOR_FILTER_OPTIONS,
  EVENT_CONTRACT_SORT_OPTIONS,
  getEventContractStatusLabel,
  getEventContractStatusVariant,
  getEventContractTypeLabel,
  getEventContractSectorLabel,
} from "../../../../constants/EventContract";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminEventContractSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const eventContractManager = useEventContractManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

  // List state
  const [eventContractList, setEventContractList] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errors, setErrors] = useState({});
  const [tagOptions, setTagOptions] = useState([]);

  // Pagination state (cursor-based)
  const [pageSize, setPageSize] = useState(25);
  const [previousCursors, setPreviousCursors] = useState([]);
  const [currentCursor, setCurrentCursor] = useState("");
  const [nextCursor, setNextCursor] = useState("");

  // Filter state
  const [sortBy, setSortBy] = useState("lexical_name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState("");
  const [type, setType] = useState("");
  const [sector, setSector] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  const searchCriteria = useMemo(() => {
    const criteria = [];
    const name = searchParams.get("name");
    const organization = searchParams.get("org");
    const customer = searchParams.get("customer");
    const startFrom = searchParams.get("start_from");
    const startTo = searchParams.get("start_to");
    const location = searchParams.get("location");
    const activeOnly = searchParams.get("active_only");

    if (name) criteria.push(`Name: ${name}`);
    if (organization) criteria.push(`Organization: ${organization}`);
    if (customer) criteria.push(`Customer: ${customer}`);
    if (startFrom) criteria.push(`Start From: ${startFrom}`);
    if (startTo) criteria.push(`Start To: ${startTo}`);
    if (location) criteria.push(`Location: ${location}`);
    if (activeOnly) criteria.push("Active Only");

    return criteria;
  }, [searchParams, tagOptions]);

  // Breadcrumb configuration
  const breadcrumbItems = [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Event Contracts",
      to: "/admin/event-contracts",
      icon: DocumentTextIcon,
    },
    {
      label: "Search",
      to: "/admin/event-contracts/search",
      icon: MagnifyingGlassIcon,
    },
    {
      label: "Results",
      isActive: true,
    },
  ];

  // Action buttons configuration
  const actionButtons = [
    {
      label: "New Search",
      variant: "secondary",
      icon: ArrowLeftIcon,
      onClick: () => navigate("/admin/event-contracts/search"),
    },
    {
      label: "Add Event Contract",
      variant: "success",
      icon: PlusIcon,
      onClick: () => navigate("/admin/event-contracts/add"),
    },
  ];

  // Handle unauthorized access
  const onUnauthorized = () => {
    navigate("/login?unauthorized=true");
  };
  // Fetch tag options on mount for label mapping
  useEffect(() => {
    const fetchTagOptions = async () => {
      try {
        const options = await tagManager.getTagSelectOptions(onUnauthorized, true);
        setTagOptions(options || []);
      } catch (error) {
        if (import.meta.env.DEV) {
          console.error("Error fetching tag options:", error);
        }
        setTagOptions([]);
      }
    };
    fetchTagOptions();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Run once on mount - tagManager and onUnauthorized are stable

  // Memoize filters map to prevent unnecessary rebuilds
  const filtersMap = useMemo(() => {
    const map = new Map();
    map.set("pageSize", pageSize);

    // Add cursor for pagination
    if (currentCursor) {
      map.set("cursor", currentCursor);
    }

    // Add sorting
    map.set("sortField", sortBy);
    map.set("sortOrder", sortOrder);

    // Add filters
    if (status !== "") {
      map.set("status", parseInt(status));
    }
    if (type !== "") {
      map.set("type", parseInt(type));
    }
    if (sector !== "") {
      map.set("sector", parseInt(sector));
    }

    // Add search params from URL
    const name = searchParams.get("name");
    const organization = searchParams.get("org");
    const customer = searchParams.get("customer");
    const startFrom = searchParams.get("start_from");
    const startTo = searchParams.get("start_to");
    const location = searchParams.get("location");
    const activeOnly = searchParams.get("active_only");

    if (name) map.set("name", name);
    if (organization) map.set("organization", organization);
    if (customer) map.set("customer", customer);
    if (startFrom) map.set("startDateFrom", startFrom);
    if (startTo) map.set("startDateTo", startTo);
    if (location) map.set("location", location);
    if (activeOnly) map.set("status", 1); // Active only

    if (searchQuery && searchQuery.trim()) {
      map.set("search", searchQuery.trim());
    }

    return map;
  }, [currentCursor, pageSize, sortBy, sortOrder, status, type, sector, searchQuery, searchParams]);

  // Fetch event contracts with useCallback to prevent infinite loops
  const fetchEventContractList = useCallback(
    (forceRefresh = false) => {
      setIsLoading(true);
      setErrors({});

      // Use the manager to fetch event contracts with force refresh flag
      eventContractManager.getEventContractsWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          setEventContractList(response);

          // Update pagination state
          if (response.hasNextPage) {
            setNextCursor(response.nextCursor);
          } else {
            setNextCursor("");
          }
        },
        (error) => {
          if (process.env.NODE_ENV === 'development') {
            console.error("Error fetching event contract list:", error);
          }
          setErrors(error);
        },
        () => {
          setIsLoading(false);
        },
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap],
  );

  // Get status badge component
  const getStatusBadge = (eventContractStatus) => {
    const variant = getEventContractStatusVariant(eventContractStatus);
    const label = getEventContractStatusLabel(eventContractStatus);

    return (
      <Badge variant={variant} size="sm">
        {label}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Event",
      accessor: "eventName",
      type: "text",
      render: (value, eventContract) => {
        const displayName = eventContract.eventName || eventContract.event?.name || "Unnamed Event";
        return (
          <div className="flex items-center">
            <DocumentTextIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>
              <div className="font-medium">{displayName}</div>
              {eventContract.organization && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {eventContract.organization}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Sector",
      accessor: "sector",
      render: (sector) => {
        if (!sector) return "—";
        return (
          <Badge variant="secondary" size="sm">
            {getEventContractSectorLabel(sector)}
          </Badge>
        );
      }
    },
    {
      header: "Facilitator",
      accessor: "facilitator",
      render: (facilitator, eventContract) => {
        const facilitatorName = eventContract.facilitatorName ||
                               (eventContract.facilitatorFirstName && eventContract.facilitatorLastName
                                 ? `${eventContract.facilitatorFirstName} ${eventContract.facilitatorLastName}`
                                 : null);

        if (!facilitatorName) return "—";

        return (
          <div className="flex items-center text-sm">
            <UserGroupIcon className={`w-4 h-4 mr-1 ${getThemeClasses('text-muted')}`} />
            {facilitatorName}
          </div>
        );
      }
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, eventContract) => (
        <ViewButton
          to={`/admin/event-contract/${eventContract.id}`}
        >
          View
        </ViewButton>
      )
    }
  ];

  // Pagination handlers
  const handlePageChange = (direction) => {
    if (direction === "next" && nextCursor) {
      const newPreviousCursors = [...previousCursors];
      newPreviousCursors.push(currentCursor);
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(nextCursor);
    } else if (direction === "previous" && previousCursors.length > 0) {
      const newPreviousCursors = [...previousCursors];
      const previousCursor = newPreviousCursors.pop();
      setPreviousCursors(newPreviousCursors);
      setCurrentCursor(previousCursor);
    }
  };

  // Search handler
  const handleSearch = () => {
    setSearchQuery(tempSearchQuery);
    // Reset pagination when search changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Filter change handlers
  const handleSortChange = (value) => {
    const [field, order] = value.split(",");
    setSortBy(field);
    setSortOrder(order);
    // Reset pagination when sort changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handleStatusChange = (value) => {
    setStatus(value);
    // Reset pagination when status changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handleTypeChange = (value) => {
    setType(value);
    // Reset pagination when type changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handleSectorChange = (value) => {
    setSector(value);
    // Reset pagination when sector changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Clear filters
  const handleClearFilters = () => {
    setSortBy("lexical_name");
    setSortOrder("ASC");
    setStatus("");
    setType("");
    setSector("");
    setSearchQuery("");
    setTempSearchQuery("");
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  };

  // Memoize search filter configuration to prevent unnecessary re-renders
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search event contracts by name...",
    statusOptions: EVENT_CONTRACT_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: EVENT_CONTRACT_TYPE_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: type,
    onTypeFilterChange: handleTypeChange,
    sortOptions: EVENT_CONTRACT_SORT_OPTIONS,
    sortValue: `${sortBy},${sortOrder}`,
    onSortChange: handleSortChange,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: () => fetchEventContractList(true)
  }), [searchQuery, tempSearchQuery, status, type, sortBy, sortOrder, pageSize]);

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    totalCount: eventContractList?.count || 0,
    hasNextPage: !!nextCursor,
    onPageChange: (direction) => {
      if (direction > previousCursors.length + 1) {
        handlePageChange("next");
      } else {
        handlePageChange("previous");
      }
    }
  }), [previousCursors.length, eventContractList?.count, nextCursor, handlePageChange]);

  // Fetch data when filters/pagination change
  useEffect(() => {
    fetchEventContractList(true);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    type,
    sector,
    searchQuery,
  ]);

  return (
    <SearchResultsPage
      breadcrumbItems={breadcrumbItems}
      searchCriteria={searchCriteria}
      pageTitle="Event Contract Search Results"
      actionButtons={actionButtons}
      results={eventContractList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      searchFilter={searchFilterConfig}
      pagination={paginationConfig}
      emptyState={{
        icon: DocumentTextIcon,
        title: "No Event Contracts Found",
        description: "No event contracts match your search criteria. Try adjusting your search terms or create a new event contract.",
        isCreateAction: true,
      }}
    />
  );
}

export default AdminEventContractSearchResultPage;