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

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { useNavigate, useSearchParams } from "react-router";
import {
  useCustomerManager,
  useAuthManager,
} from "../../../../services/Services";
import {
  UserPlusIcon,
  UserGroupIcon,
  EnvelopeIcon,
  PhoneIcon,
  MapPinIcon,
  AcademicCapIcon,
  HeartIcon,
  BuildingOfficeIcon,
  BuildingOffice2Icon,
} from "@heroicons/react/24/outline";
import {
  WizardSearchResults,
  SelectButton,
  UIXThemeProvider,
  Badge,
} from "../../../../components/UIX";
import { useUIXTheme } from "../../../../components/UIX/themes/useUIXTheme.jsx";
import { PAGE_SIZE_OPTIONS } from "../../../../constants/FieldOptions";
import {
  CUSTOMER_TYPE_VALUES,
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STATUS,
  CUSTOMER_STATUS_LABELS,
} from "../../../../constants/Customer";

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

// Sort options - moved outside component
const SORT_OPTIONS = [
  { value: "name,ASC", label: "Name (A-Z)" },
  { value: "name,DESC", label: "Name (Z-A)" },
  { value: "createdAt,ASC", label: "Created Date (Oldest)" },
  { value: "createdAt,DESC", label: "Created Date (Newest)" },
];

// Status filter options - moved outside component
const STATUS_FILTER_OPTIONS = [
  { value: "", label: "All Statuses" },
  { value: String(CUSTOMER_STATUS.ACTIVE), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.ACTIVE] },
  { value: String(CUSTOMER_STATUS.ARCHIVED), label: CUSTOMER_STATUS_LABELS[CUSTOMER_STATUS.ARCHIVED] },
];

// Type filter options - moved outside component
const TYPE_FILTER_OPTIONS = [
  { value: "", label: "All Types" },
  { value: String(CUSTOMER_TYPE_VALUES.EDUCATIONAL), label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.EDUCATIONAL] },
  { value: String(CUSTOMER_TYPE_VALUES.CORPORATE), label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.CORPORATE] },
  { value: String(CUSTOMER_TYPE_VALUES.NON_PROFIT), label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.NON_PROFIT] },
  { value: String(CUSTOMER_TYPE_VALUES.GOVERNMENT), label: CUSTOMER_TYPE_LABELS[CUSTOMER_TYPE_VALUES.GOVERNMENT] },
];

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

  // URL Parameters
  const firstName = searchParams.get("fn") || "";
  const lastName = searchParams.get("ln") || "";
  const email = searchParams.get("e") || "";
  const phone = searchParams.get("p") || "";

  // Component state
  const [errors, setErrors] = useState({});
  const [customerList, setCustomerList] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [pageSize, setPageSize] = useState(50);
  const [previousCursors, setPreviousCursors] = useState([]);
  const [nextCursor, setNextCursor] = useState("");
  const [currentCursor, setCurrentCursor] = useState("");
  const [searchQuery, setSearchQuery] = useState("");
  const [tempSearchQuery, setTempSearchQuery] = useState("");
  const [status, setStatus] = useState("");
  const [typeOf, setTypeOf] = useState("");
  const [sortByValue, setSortByValue] = useState("name,ASC");

  // Check authentication
  useEffect(() => {
    if (!authManager.isAuthenticated()) {
      navigate("/login");
      return;
    }
  }, [authManager, navigate]);

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

  // Memoize filters map to prevent unnecessary rebuilds
  const filtersMap = useMemo(() => {
    const map = new Map();

    // Pagination
    map.set("page_size", pageSize);
    map.set("sort_field", "name"); // Default sort field

    if (currentCursor) {
      map.set("cursor", currentCursor);
    }

    // Sorting - split the sortByValue
    if (sortByValue) {
      const sortArray = sortByValue.split(",");
      map.set("sort_field", sortArray[0]);
      map.set("sort_order", sortArray[1]);
    }

    // Search parameters - using snake_case as the backend expects
    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);
    }

    // Additional filters
    if (searchQuery) {
      map.set("search", searchQuery);
    }
    if (status) {
      map.set("status", status);
    }
    if (typeOf) {
      map.set("type", typeOf);
    }

    return map;
  }, [currentCursor, pageSize, sortByValue, firstName, lastName, email, phone, searchQuery, status, typeOf]);

  // Fetch customers based on search parameters
  const fetchCustomers = useCallback(async (forceRefresh = false) => {
    setIsLoading(true);
    setErrors({});

    try {
      const customersData = await customerManager.getCustomersWithFiltersMap(
        filtersMap,
        onUnauthorized,
        forceRefresh,
      );

      setCustomerList(customersData);
      if (customersData.hasNextPage) {
        setNextCursor(customersData.nextCursor);
      } else {
        setNextCursor("");
      }
    } catch (error) {
      setErrors({ message: error.message || "An unexpected error occurred." });
    } finally {
      setIsLoading(false);
    }
  }, [customerManager, filtersMap, onUnauthorized]);

  // Fetch customers on mount and when filters/pagination change
  useEffect(() => {
    fetchCustomers(true);
  }, [fetchCustomers]);

  // Get customer type icon - memoized
  const getCustomerTypeIcon = useCallback((type) => {
    switch (type) {
      case CUSTOMER_TYPE_VALUES.EDUCATIONAL:
        return <AcademicCapIcon className={`w-5 h-5 ${getThemeClasses('text-info')}`} />;
      case CUSTOMER_TYPE_VALUES.CORPORATE:
        return <BuildingOffice2Icon className={`w-5 h-5 ${getThemeClasses('text-success')}`} />;
      case CUSTOMER_TYPE_VALUES.NON_PROFIT:
        return <HeartIcon className={`w-5 h-5 ${getThemeClasses('text-accent')}`} />;
      case CUSTOMER_TYPE_VALUES.GOVERNMENT:
        return <BuildingOfficeIcon className={`w-5 h-5 ${getThemeClasses('text-warning')}`} />;
      default:
        return <UserGroupIcon className={`w-5 h-5 ${getThemeClasses('text-muted')}`} />;
    }
  }, [getThemeClasses]);

  // Format phone number - memoized
  const formatPhone = useCallback((phone) => {
    if (!phone) return "—";
    const cleaned = phone.replace(/\D/g, "");
    const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
    if (match) {
      return `(${match[1]}) ${match[2]}-${match[3]}`;
    }
    return phone;
  }, []);

  // Handle customer selection - memoized
  const handleSelectCustomer = useCallback((customer) => {
    navigate(`/admin/customers/${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">
            {getCustomerTypeIcon(customer.type)}
            <div className="ml-2">
              <div className="font-medium">{displayName}</div>
              {customer.type && (
                <div className={`text-sm ${getThemeClasses('text-secondary')}`}>
                  {CUSTOMER_TYPE_LABELS[customer.type] || customer.type}
                </div>
              )}
            </div>
          </div>
        );
      }
    },
    {
      header: "Location",
      accessor: "address",
      render: (address, customer) => {
        if (!customer.address) return "—";
        return (
          <div className="flex items-center text-sm">
            <MapPinIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
            <div>{customer.address}</div>
          </div>
        );
      }
    },
    {
      header: "Contact",
      accessor: "email",
      render: (email, customer) => {
        return (
          <div className="space-y-1">
            {customer.email && (
              <div className="flex items-center text-sm">
                <EnvelopeIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`mailto:${customer.email}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {customer.email}
                </a>
              </div>
            )}
            {customer.phone && (
              <div className="flex items-center text-sm">
                <PhoneIcon className={`w-4 h-4 mr-2 ${getThemeClasses('text-muted')}`} />
                <a
                  href={`tel:${customer.phone}`}
                  className={`transition-colors ${getThemeClasses('link-primary')}`}
                  onClick={(e) => e.stopPropagation()}
                >
                  {formatPhone(customer.phone)}
                </a>
              </div>
            )}
          </div>
        );
      }
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, customer) => (
        <SelectButton onClick={() => handleSelectCustomer(customer)}>
          Select
        </SelectButton>
      )
    }
  ], [getCustomerTypeIcon, formatPhone, handleSelectCustomer]); // getThemeClasses removed - captured in closure

  // Pagination handlers
  const handlePageChange = useCallback((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);
    }
  }, [nextCursor, previousCursors, currentCursor]);

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

  // Filter change handlers
  const handleSortChange = useCallback((value) => {
    setSortByValue(value);
    // Reset pagination when sort changes
    setPreviousCursors([]);
    setCurrentCursor("");
    setNextCursor("");
  }, []);

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

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

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

  // Clear filters - memoized
  const handleClearFilters = useCallback(() => {
    setSortByValue("name,ASC");
    setStatus("");
    setTypeOf("");
    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 customers by name, email, or phone...",
    statusOptions: STATUS_FILTER_OPTIONS,
    statusFilter: status,
    onStatusFilterChange: handleStatusChange,
    typeOptions: TYPE_FILTER_OPTIONS,
    typeFilter: typeOf,
    onTypeFilterChange: handleTypeChange,
    sortOptions: SORT_OPTIONS,
    sortValue: sortByValue,
    onSortChange: handleSortChange,
    pageSizeOptions: PAGE_SIZE_OPTIONS.map(opt => ({
      value: opt.value,
      label: opt.label
    })),
    pageSize,
    onPageSizeChange: handlePageSizeChange,
    onClearFilters: handleClearFilters,
    onRefresh: () => fetchCustomers(true)
  }), [searchQuery, tempSearchQuery, status, typeOf, sortByValue, pageSize, handleSearch, handleStatusChange, handleTypeChange, handleSortChange, handlePageSizeChange, handleClearFilters, fetchCustomers]);

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

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

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

  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}
        onSearchAgain={handleSearchAgain}
        onAddNew={handleAddNew}
        entityName="customer"
        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,
        }}
      />
    </UIXThemeProvider>
  );
}

export default AdminCustomerAddStep1PartBPage;
