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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Link, useNavigate, useSearchParams } from "react-router";
import { useEventOrderManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  EyeIcon,
  TicketIcon,
  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_ORDER_STATUS_FILTER_OPTIONS,
  EVENT_ORDER_SECTOR_FILTER_OPTIONS,
  EVENT_ORDER_SORT_OPTIONS,
  getEventOrderStatusLabel,
  getEventOrderStatusVariant,
  getEventOrderSectorLabel,
} from "../../../../constants/EventOrder";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

function AdminEventOrderSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const eventOrderManager = useEventOrderManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

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

  // Pagination state (offset-based)
  const [pageSize, setPageSize] = useState(25);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);

  // Filter state
  const [sortBy, setSortBy] = useState("lexical_name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = 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 orderFrom = searchParams.get("order_from");
    const orderTo = searchParams.get("order_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 (orderFrom) criteria.push(`Order From: ${orderFrom}`);
    if (orderTo) criteria.push(`Order To: ${orderTo}`);
    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 Orders",
      to: "/admin/event-orders",
      icon: TicketIcon,
    },
    {
      label: "Search",
      to: "/admin/event-orders/search",
      icon: MagnifyingGlassIcon,
    },
    {
      label: "Results",
      isActive: true,
    },
  ];

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

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

  // Memoize API parameters to prevent unnecessary rebuilds
  const apiParams = useMemo(() => {
    const params = {
      page: currentPage,
      limit: pageSize,
    };

    // Add sorting
    params.sortField = sortBy;
    params.sortOrder = sortOrder;

    // Add filters
    if (status !== "") {
      params.status = parseInt(status);
    }
    if (sector !== "") {
      params.sector = parseInt(sector);
    }

    // Add search params from URL
    const name = searchParams.get("name");
    const organization = searchParams.get("org");
    const customer = searchParams.get("customer");
    const orderFrom = searchParams.get("order_from");
    const orderTo = searchParams.get("order_to");
    const location = searchParams.get("location");
    const activeOnly = searchParams.get("active_only");

    if (name) params.name = name;
    if (organization) params.organization = organization;
    if (customer) params.customer = customer;
    if (orderFrom) params.orderDateFrom = orderFrom;
    if (orderTo) params.orderDateTo = orderTo;
    if (location) params.location = location;
    if (activeOnly) params.status = 1; // Active only

    if (searchQuery && searchQuery.trim()) {
      params.search = searchQuery.trim();
    }

    return params;
  }, [currentPage, pageSize, sortBy, sortOrder, status, sector, searchQuery, searchParams]);

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

      // Use the manager to fetch event orders
      eventOrderManager.getEventOrders(
        apiParams,
        onUnauthorized,
        forceRefresh,
      )
      .then((response) => {
        setEventOrderList(response);
        setTotalPages(Math.ceil((response.count || 0) / pageSize));
      })
      .catch((error) => {
        if (process.env.NODE_ENV === 'development') {
          console.error("Error fetching event order list:", error);
        }
        setErrors({ message: "Failed to load event orders. Please try again." });
      })
      .finally(() => {
        setIsLoading(false);
      });
    },
    [apiParams, eventOrderManager, onUnauthorized, pageSize],
  );

  // Get status badge component
  const getStatusBadge = (eventOrderStatus) => {
    const variant = getEventOrderStatusVariant(eventOrderStatus);
    const label = getEventOrderStatusLabel(eventOrderStatus);

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

  // Column configuration for DataList
  const columns = [
    {
      header: "Event Order",
      accessor: "name",
      type: "text",
      render: (value, eventOrder) => {
        const displayName = eventOrder.name || "Unnamed Order";
        return (
          <div className="flex items-center">
            <TicketIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>
              <div className="font-medium">{displayName}</div>
              {eventOrder.organization && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {eventOrder.organization}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Customer",
      accessor: "customer",
      render: (customer, eventOrder) => {
        if (!customer && !eventOrder.customerName) return "—";
        return (
          <div className="flex items-center">
            <UserGroupIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
            <span>{customer || eventOrder.customerName}</span>
          </div>
        );
      }
    },
    {
      header: "Sector",
      accessor: "sector",
      render: (sector) => {
        if (!sector) return "—";
        return (
          <Badge variant="secondary" size="sm">
            {getEventOrderSectorLabel(sector)}
          </Badge>
        );
      }
    },
    {
      header: "Order Date",
      accessor: "orderDate",
      render: (orderDate) => {
        if (!orderDate) return "—";
        return (
          <div className="flex items-center text-sm">
            <CalendarIcon className={`w-4 h-4 mr-1 ${getThemeClasses('text-muted')}`} />
            {formatDateForDisplay(orderDate)}
          </div>
        );
      }
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, eventOrder) => (
        <ViewButton
          onClick={() => navigate(`/admin/event-order/${eventOrder.id}`)}
        >
          View
        </ViewButton>
      )
    }
  ];

  // Search handler
  const handleSearch = () => {
    setSearchQuery(tempSearchQuery);
    // Reset pagination when search changes
    setCurrentPage(1);
  };

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

  const handleStatusChange = (value) => {
    setStatus(value);
    // Reset pagination when status changes
    setCurrentPage(1);
  };

  const handleSectorChange = (value) => {
    setSector(value);
    // Reset pagination when sector changes
    setCurrentPage(1);
  };

  const handlePageSizeChange = (value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setCurrentPage(1);
  };

  // Clear filters
  const handleClearFilters = () => {
    setSortBy("lexical_name");
    setSortOrder("ASC");
    setStatus("");
    setSector("");
    setSearchQuery("");
    setTempSearchQuery("");
    setCurrentPage(1);
  };

  // Memoize search filter configuration to prevent unnecessary re-renders
  const searchFilterConfig = useMemo(() => ({
    searchTerm: searchQuery,
    tempSearchTerm: tempSearchQuery,
    onSearchTermChange: setTempSearchQuery,
    onSearch: handleSearch,
    searchPlaceholder: "Search event orders by name...",
    statusOptions: EVENT_ORDER_STATUS_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: EVENT_ORDER_SECTOR_FILTER_OPTIONS.map(opt => ({
      value: opt.value.toString(),
      label: opt.label
    })),
    typeFilter: sector,
    onTypeFilterChange: handleSectorChange,
    sortOptions: EVENT_ORDER_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: () => fetchEventOrderList(true)
  }), [searchQuery, tempSearchQuery, status, sector, sortBy, sortOrder, pageSize, handleSearch, handleStatusChange, handleSectorChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchEventOrderList]);

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(() => ({
    currentPage,
    totalCount: eventOrderList?.count || 0,
    totalPages,
    hasNextPage: currentPage < totalPages,
    onPageChange: (page) => setCurrentPage(page)
  }), [currentPage, eventOrderList?.count, totalPages]);

  // Initial load effect
  useEffect(() => {
    fetchEventOrderList(true);
  }, []);

  // Effect for filter changes and pagination
  useEffect(() => {
    if (searchQuery || currentPage > 1) {
      fetchEventOrderList(true);
    }
  }, [
    currentPage,
    pageSize,
    sortBy,
    sortOrder,
    status,
    sector,
    searchQuery,
  ]);

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

export default AdminEventOrderSearchResultPage;