// File Path: monorepo/web/frontend/src/pages/Admin/Customer/Add/Step1ResultsPage.jsx

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import { useCustomerManager } from "../../../../services/Services";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
  Badge,
  useUIXTheme,
} from "../../../../components/UIX";
import {
  UserGroupIcon,
  UserIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  CalendarIcon,
  BuildingOfficeIcon,
} from "@heroicons/react/24/outline";
import { PAGE_SIZE_OPTIONS } from "../../../../constants/FieldOptions";
import {
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STATUS,
  CUSTOMER_STATUS_LABELS,
} from "../../../../constants/Customer";
import { formatDateForDisplay } from "../../../../services/Helpers/DateFormatter";

// Configuration for wizard steps - moved outside component
const WIZARD_STEPS = [
  { title: "Search" },
  { title: "Type" },
  { title: "Contact" },
  { title: "Address" },
  { title: "Account" },
  { title: "Metrics" },
  { title: "Comments" },
];

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

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

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

  // Filter state
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");

  // Extract search parameters from URL
  useEffect(() => {
    const urlParams = new URLSearchParams(location.search);
    const firstName = urlParams.get("fn") || "";
    const lastName = urlParams.get("ln") || "";
    const email = urlParams.get("e") || "";
    const phone = urlParams.get("p") || "";

    // Build search query from parameters
    const searchTerms = [firstName, lastName, email, phone].filter(Boolean);
    if (searchTerms.length > 0) {
      setSearchQuery(searchTerms.join(" "));
      setTempSearchQuery(searchTerms.join(" "));
    }
  }, [searchParams]);

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

  // Memoize API parameters to prevent unnecessary rebuilds
  const apiParams = useMemo(() => {
    const params = {
      page: currentPage,
      limit: pageSize,
      status: String(CUSTOMER_STATUS.ACTIVE), // Active customers only
    };

    // Add search params from URL
    const urlParams = new URLSearchParams(location.search);
    const firstName = urlParams.get("fn");
    const lastName = urlParams.get("ln");
    const email = urlParams.get("e");
    const phone = urlParams.get("p");

    if (firstName) params.firstName = firstName;
    if (lastName) params.lastName = lastName;
    if (email) params.email = email;
    if (phone) params.phone = phone;
    if (searchQuery && searchQuery.trim()) params.search = searchQuery.trim();

    return params;
  }, [currentPage, pageSize, searchQuery]);

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

      // Use the manager to fetch customers
      customerManager
        .getCustomers(apiParams, onUnauthorized, forceRefresh)
        .then((response) => {
          setCustomerList(response);
          setTotalPages(Math.ceil((response.count || 0) / pageSize));
        })
        .catch((error) => {
          if (import.meta.env.DEV) {
            console.error("Error fetching customer list:", error);
          }
          setErrors({ message: "Failed to load customers. Please try again." });
        })
        .finally(() => {
          setIsLoading(false);
        });
    },
    [apiParams, customerManager, onUnauthorized, pageSize],
  );

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

  // Filter change handlers - memoized
  const handlePageSizeChange = useCallback((value) => {
    setPageSize(value);
    // Reset pagination when page size changes
    setCurrentPage(1);
  }, []);

  // Clear filters - memoized
  const handleClearFilters = useCallback(() => {
    setSearchQuery("");
    setTempSearchQuery("");
    setCurrentPage(1);
  }, []);

  // Get badge component for customer type - memoized
  const getTypeBadge = useCallback((customerType) => {
    return (
      <Badge variant={customerType === 2 ? "primary" : "secondary"} size="sm">
        {customerType === 2 ? "Business" : "Individual"}
      </Badge>
    );
  }, []);

  // Handle customer selection - memoized
  const handleSelectCustomer = useCallback(
    (customer) => {
      // Store selected customer data
      sessionStorage.setItem(
        "FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE",
        JSON.stringify({
          selectedCustomer: customer,
        }),
      );
      // Navigate to customer detail page
      navigate(`/admin/customer/${customer.id}`);
    },
    [navigate],
  );

  // 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.organization && (
                  <div
                    className={`text-sm ${getThemeClasses("text-secondary")}`}
                  >
                    {customer.organization}
                  </div>
                )}
              </div>
            </div>
          );
        },
      },
      {
        header: "Contact",
        accessor: "email",
        render: (email, customer) => {
          if (!email && !customer.phone) return null;
          return (
            <div className="space-y-1">
              {email && (
                <div className="flex items-center text-sm">
                  <EnvelopeIcon
                    className={`w-4 h-4 mr-2 ${getThemeClasses("text-muted")}`}
                  />
                  <a
                    href={`mailto:${email}`}
                    className={`transition-colors ${getThemeClasses("link-primary")}`}
                    onClick={(e) => e.stopPropagation()}
                  >
                    {email}
                  </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: "Location",
        accessor: "city",
        render: (city, customer) => {
          if (!customer.city && !customer.region) return "—";
          return (
            <div
              className={`flex items-center text-sm ${getThemeClasses("text-secondary")}`}
            >
              <MapPinIcon
                className={`w-4 h-4 mr-1 ${getThemeClasses("text-muted")}`}
              />
              {[customer.city, customer.region].filter(Boolean).join(", ")}
            </div>
          );
        },
      },
      {
        header: "Type",
        accessor: "type",
        render: (type) => getTypeBadge(type),
      },
      {
        header: "Member Since",
        accessor: "createdAt",
        render: (createdAt) => (
          <div
            className={`flex items-center text-sm ${getThemeClasses("text-secondary")}`}
          >
            <CalendarIcon
              className={`w-4 h-4 mr-1 ${getThemeClasses("text-muted")}`}
            />
            {formatDateForDisplay(createdAt)}
          </div>
        ),
      },
      {
        header: "Actions",
        align: "right",
        type: "action",
        render: (value, customer) => (
          <SelectButton onClick={() => handleSelectCustomer(customer)}>
            Select
          </SelectButton>
        ),
      },
    ],
    [getTypeBadge, handleSelectCustomer],
  ); // getThemeClasses removed - captured in closure

  // 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, email, or phone...",
      statusOptions: [], // No status filter for customers in this context
      statusFilter: "",
      onStatusFilterChange: () => {},
      typeOptions: [], // No type filter for customers in this context
      typeFilter: "",
      onTypeFilterChange: () => {},
      sortOptions: [], // No sorting for customers in this context
      sortValue: "",
      onSortChange: () => {},
      pageSizeOptions: PAGE_SIZE_OPTIONS.map((opt) => ({
        value: opt.value,
        label: opt.label,
      })),
      pageSize,
      onPageSizeChange: handlePageSizeChange,
      onClearFilters: handleClearFilters,
      onRefresh: () => fetchCustomerList(true),
    }),
    [
      searchQuery,
      tempSearchQuery,
      pageSize,
      handleSearch,
      handlePageSizeChange,
      handleClearFilters,
      fetchCustomerList,
    ],
  );

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

  // Action handlers - memoized
  const handleSearchAgain = useCallback(() => {
    navigate("/admin/customers/add/step-1-part-a");
  }, [navigate]);

  const handleAddNew = useCallback(() => {
    // Clear any existing customer creation state
    sessionStorage.removeItem("FLASHPOINTTRAINING_CUSTOMER_CREATION_STATE");
    // Navigate directly to step 2
    navigate("/admin/customers/add/step-2");
  }, [navigate]);

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

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

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={WIZARD_STEPS}
        currentStep={1}
        wizardTitle="Add New Customer"
        wizardIcon={UserGroupIcon}
        data={customerList?.results || []}
        columns={columns}
        isLoading={isLoading}
        errors={errors}
        searchFilter={searchFilterConfig}
        pagination={paginationConfig}
        entityName="customer"
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
        emptyState={{
          icon: UserIcon,
          title: "No Customers Found",
          description:
            "No customers match your search criteria. Try adjusting your search terms or create a new customer.",
        }}
      />
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep1ResultsPage;
