// File Path: monorepo/web/frontend/src/pages/Admin/EventOrder/Add/Step2PartBPage.jsx

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

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

  // Configuration for wizard steps
  const wizardSteps = [
    { title: "Find Event" },
    { title: "Find Customer" },
    { title: "Order Requirements" },
    { title: "Additional Details" },
    { title: "Review & Confirm" },
  ];

  // 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("");

  // Check for event selection on mount
  useEffect(() => {
    const event = wizardStorage.getEvent();
    if (!event) {
      // No event selected, redirect back to step 1
      navigate("/admin/event-orders/add/step-1-search");
      return;
    }
  }, [navigate, wizardStorage]);

  // Extract search parameters from URL on mount
  useEffect(() => {
    const urlSearchQuery = searchParams.get("q") || "";
    const email = searchParams.get("email") || "";
    const phone = searchParams.get("phone") || "";
    const firstName = searchParams.get("firstName") || "";
    const lastName = searchParams.get("lastName") || "";

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

  // 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,
      status: "1", // Active customers only
    };

    // Get URL params
    const urlSearchQuery = searchParams.get("q");
    const urlEmail = searchParams.get("email");
    const urlPhone = searchParams.get("phone");
    const urlFirstName = searchParams.get("firstName");
    const urlLastName = searchParams.get("lastName");

    // Priority: Use searchQuery (from search field) over URL params
    if (searchQuery && searchQuery.trim()) {
      params.search = searchQuery.trim();
    } else if (
      urlSearchQuery ||
      urlEmail ||
      urlPhone ||
      urlFirstName ||
      urlLastName
    ) {
      // Use URL params
      if (urlSearchQuery) {
        params.search = urlSearchQuery;
      }
      if (urlEmail) params.email = urlEmail;
      if (urlPhone) params.phone = urlPhone;
      if (urlFirstName) params.firstName = urlFirstName;
      if (urlLastName) params.lastName = urlLastName;
    }

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

  // 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 (process.env.NODE_ENV === "development") {
            console.error("Error fetching customer list:", error);
          }
          setErrors({ message: "Failed to load customers. Please try again." });
        })
        .finally(() => {
          setIsLoading(false);
        });
    },
    [apiParams, customerManager, pageSize],
  );

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

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

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

  // Get badge component for customer type
  const getTypeBadge = (customerType) => {
    const colorMap = {
      1: getThemeClasses("badge-secondary"), // Individual
      2: getThemeClasses("badge-primary"), // Business
    };
    const colorClass =
      colorMap[customerType] || getThemeClasses("badge-neutral");

    return (
      <Badge variant={customerType === 2 ? "primary" : "secondary"} size="sm">
        {customerType === 2 ? "Business" : "Individual"}
      </Badge>
    );
  };

  // Column configuration for DataList
  const columns = [
    {
      header: "Customer",
      accessor: "name",
      type: "text",
      render: (value, customer) => {
        const displayName =
          customer.name || `${customer.firstName} ${customer.lastName}`;
        return (
          <div>
            <div className="font-medium">{displayName}</div>
            {customer.organization && (
              <div className={`text-sm ${getThemeClasses("text-secondary")}`}>
                {customer.organization}
              </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" />
            {[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" />
          {formatDateForDisplay(createdAt)}
        </div>
      ),
    },
    {
      header: "Actions",
      align: "right",
      type: "action",
      render: (value, customer) => (
        <SelectButton onClick={() => handleSelectCustomer(customer)}>
          Select
        </SelectButton>
      ),
    },
  ];

  // Handle customer selection
  const handleSelectCustomer = (customer) => {
    // Store selected customer data
    wizardStorage.setCustomer(customer);
    // Navigate to step 3 (Order Requirements)
    navigate("/admin/event-orders/add/step-3");
  };

  // 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 event orders
      statusFilter: "",
      onStatusFilterChange: () => {},
      typeOptions: [], // No type filter for customers in event orders
      typeFilter: "",
      onTypeFilterChange: () => {},
      sortOptions: [], // No sorting for customers in event orders
      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
  const handleSearchAgain = () => {
    navigate("/admin/event-orders/add/step-2-search");
  };

  const handleAddNew = () => {
    // Navigate to customer creation
    navigate("/admin/customers/add/step-1-search");
  };

  // Effect for fetching customer list when params change
  useEffect(() => {
    // Always fetch, even with empty search
    fetchCustomerList(true);
  }, [currentPage, pageSize, searchQuery]); // Don't depend on fetchCustomerList itself

  return (
    <UIXThemeProvider>
      <WizardSearchResults
        wizardSteps={wizardSteps}
        currentStep={2}
        wizardTitle="Create Event Order"
        wizardIcon={TicketIcon}
        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 AdminEventOrderAddStep2PartBPage;
