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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { useCustomerManager } from "../../../../services/Services";
import {
  MagnifyingGlassIcon,
  ArrowLeftIcon,
  UserGroupIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  BuildingOffice2Icon,
  MapPinIcon,
  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 { CUSTOMER_STATUS } from "../../../../constants/Customer";

function AdminCustomerSearchResultPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const customerManager = useCustomerManager();
  const tagManager = useTagManager();
  const { getThemeClasses } = useUIXTheme();

  // Extract search parameters from URL
  const firstName = searchParams.get("fn") || "";
  const lastName = searchParams.get("ln") || "";
  const email = searchParams.get("e") || "";
  const phone = searchParams.get("p") || "";
  const organizationName = searchParams.get("on") || "";
  const isActive = searchParams.get("active") === "1";

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

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

  // Filter state
  const [sortBy, setSortBy] = useState("last_name");
  const [sortOrder, setSortOrder] = useState("ASC");
  const [status, setStatus] = useState(isActive ? "1" : "");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search criteria for display
  const searchCriteria = useMemo(() => {
    const criteria = [];
    if (firstName) criteria.push(`First Name: ${firstName}`);
    if (lastName) criteria.push(`Last Name: ${lastName}`);
    if (email) criteria.push(`Email: ${email}`);
    if (phone) criteria.push(`Phone: ${phone}`);
    if (organizationName) criteria.push(`Organization: ${organizationName}`);
    if (tags) {
      // Map tag IDs to labels
      const tagIds = tags.split(",");
      const tagLabels = tagIds
        .map((tagId) => {
          const tag = tagOptions.find((opt) => opt.value === tagId);
          return tag ? tag.label : tagId;
        })
        .join(", ");
      criteria.push(`Tags: ${tagLabels}`);
    }
    if (isActive) criteria.push("Active Only");
    return criteria;
  }, [firstName, lastName, email, phone, organizationName, isActive]);

  // Breadcrumb configuration - memoized
  const breadcrumbItems = useMemo(() => [
    {
      label: "Dashboard",
      to: "/admin/dashboard",
      icon: HomeIcon,
    },
    {
      label: "Customers",
      to: "/admin/customers",
      icon: UserGroupIcon,
    },
    {
      label: "Search",
      to: "/admin/customers/search",
      icon: MagnifyingGlassIcon,
    },
    {
      label: "Results",
      isActive: true,
    },
  ], []);

  // Action buttons configuration - memoized
  const actionButtons = useMemo(() => [
    {
      label: "New Search",
      variant: "secondary",
      icon: ArrowLeftIcon,
      onClick: () => navigate("/admin/customers/search"),
    },
    {
      label: "Add Customer",
      variant: "success",
      icon: PlusIcon,
      onClick: () => navigate("/admin/customers/add/step-1-search"),
    },
  ], [navigate]);

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

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

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

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

    // Add search params from URL
    if (firstName) map.set("first_name", firstName);
    if (lastName) map.set("last_name", lastName);
    if (email) map.set("email", email);
    if (phone) map.set("phone", phone);
    if (organizationName) map.set("organization_name", organizationName);

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

    return map;
  }, [currentCursor, pageSize, sortBy, sortOrder, status, searchQuery, firstName, lastName, email, phone, organizationName]);

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

      customerManager.getCustomersWithFiltersMapWithCallbacks(
        filtersMap,
        (response) => {
          setCustomerList(response);
        },
        (error) => {
          if (import.meta.env.DEV) {
            console.error("Error fetching customer list:", error);
          }
          setErrors(error);
        },
        () => {
          setIsLoading(false);
        },
        onUnauthorized,
        forceRefresh,
      );
    },
    [filtersMap, customerManager, onUnauthorized],
  );

  // Get status badge component - memoized
  const getStatusBadge = useCallback((customerStatus) => {
    const variantMap = {
      [CUSTOMER_STATUS.ACTIVE]: "success",
      [CUSTOMER_STATUS.ARCHIVED]: "secondary",
    };
    const variant = variantMap[customerStatus] || "default";
    const label = customerStatus === CUSTOMER_STATUS.ACTIVE ? "Active" : "Inactive";

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

  // Get type badge component - memoized
  const getTypeBadge = useCallback((customerType) => {
    const typeLabels = {
      1: "Educational",
      2: "Corporate",
      3: "Non-Profit",
      4: "Government",
    };

    const variantMap = {
      1: "info",
      2: "primary",
      3: "warning",
      4: "secondary",
    };

    const label = typeLabels[customerType] || "Unknown";
    const variant = variantMap[customerType] || "default";

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

  // Column configuration for DataList - memoized
  const columns = useMemo(() => [
    {
      header: "Customer",
      accessor: "name",
      type: "text",
      render: (value, customer) => {
        const displayName = customer.name || `${customer.firstName} ${customer.lastName}`;
        return (
          <div className="flex items-center">
            <UserIcon className={`w-5 h-5 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>
              <div className="font-medium">{displayName}</div>
              {customer.organizationName && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {customer.organizationName}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (customerEmail, customer) => {
        return (
          <div className="space-y-1">
            {customerEmail && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`mailto:${customerEmail}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {customerEmail}
                </a>
              </div>
            )}
            {customer.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <span>{customer.phone}</span>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Type",
      accessor: "type",
      render: (type) => getTypeBadge(type)
    },
    {
      header: "Status",
      accessor: "status",
      render: (status) => getStatusBadge(status)
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, customer) => (
        <ViewButton
          to={`/admin/customer/${customer.id}`}
        >
          View
        </ViewButton>
      )
    }
  ], [getStatusBadge, getTypeBadge]); // getThemeClasses removed - captured in closure

  // Pagination handlers - memoized
  const handlePageChange = useCallback((direction) => {
    if (direction === "next" && customerList?.hasNextPage) {
      setPreviousCursors(prev => [...prev, currentCursor]);
      setCurrentCursor(customerList.nextCursor);
    } else if (direction === "prev" && previousCursors.length > 0) {
      const newPrevious = [...previousCursors];
      const prevCursor = newPrevious.pop();
      setPreviousCursors(newPrevious);
      setCurrentCursor(prevCursor || "");
    }
  }, [currentCursor, customerList?.hasNextPage, customerList?.nextCursor, previousCursors]);

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

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

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

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

  // Clear filters - memoized
  const handleClearFilters = useCallback(() => {
    setSortBy("last_name");
    setSortOrder("ASC");
    setStatus("");
    setSearchQuery("");
    setTempSearchQuery("");
    setCurrentCursor("");
    setPreviousCursors([]);
  }, []);

  // Status filter options - memoized
  const statusFilterOptions = useMemo(() => [
    { value: "", label: "All Statuses" },
    { value: "1", label: "Active" },
    { value: "0", label: "Inactive" },
  ], []);

  // Sort options - memoized
  const sortOptions = useMemo(() => [
    { value: "last_name,ASC", label: "Last Name (A → Z)" },
    { value: "last_name,DESC", label: "Last Name (Z → A)" },
    { value: "lexical_name,ASC", label: "Name (A → Z)" },
    { value: "lexical_name,DESC", label: "Name (Z → A)" },
    { value: "created_at,DESC", label: "Created Date (Newest → Oldest)" },
    { value: "created_at,ASC", label: "Created Date (Oldest → Newest)" },
  ], []);

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

  // Memoize pagination configuration to prevent unnecessary re-renders
  const paginationConfig = useMemo(() => ({
    currentPage: previousCursors.length + 1,
    hasNextPage: customerList?.hasNextPage || false,
    hasPreviousPage: previousCursors.length > 0,
    totalCount: customerList?.count || 0,
    pageSize,
    onPageChange: handlePageChange
  }), [previousCursors.length, customerList?.hasNextPage, customerList?.count, pageSize, handlePageChange]);

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

  // Effect for filter changes and pagination
  useEffect(() => {
    if (searchQuery || currentCursor !== "" || status !== "") {
      fetchCustomerList(true);
    }
  }, [
    currentCursor,
    pageSize,
    sortBy,
    sortOrder,
    status,
    searchQuery,
    fetchCustomerList,
  ]);

  return (
    <SearchResultsPage
      breadcrumbItems={breadcrumbItems}
      searchCriteria={searchCriteria}
      pageTitle="Customer Search Results"
      actionButtons={actionButtons}
      results={customerList?.results || []}
      columns={columns}
      isLoading={isLoading}
      errors={errors}
      searchFilter={searchFilterConfig}
      pagination={paginationConfig}
      emptyState={{
        icon: UserGroupIcon,
        title: "No Customers Found",
        description: "No customers match your search criteria. Try adjusting your search terms or create a new customer.",
        isCreateAction: true,
      }}
    />
  );
}

export default AdminCustomerSearchResultPage;