import React, { useState, useEffect } from 'react';
import { apiClient } from "@/utils/apiClient";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Search, ChevronsUpDown, X, ChevronUp, ChevronDown } from 'lucide-react';
import { toast } from 'sonner';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { Badge } from "@/components/ui/badge";
import { TemplateForm } from '@/components/templates/TemplateForm';

interface ProductSearchDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onTemplateCreated: () => void;
}

interface Product {
  pid: number;
  title: string;
  description: string;
  sku: string;
  barcode: string;
  harmonized_tariff_code: string;
  price: number;
  regular_price: number;
  cost_price: number;
  vendor: string;
  vendor_reference: string;
  notions_reference: string;
  brand: string;
  brand_id: string;
  line: string;
  line_id: string;
  subline: string;
  subline_id: string;
  artist: string;
  artist_id: string;
  moq: number;
  weight: number;
  length: number;
  width: number;
  height: number;
  country_of_origin: string;
  total_sold: number;
  first_received: string | null;
  date_last_sold: string | null;
  supplier?: string;
  categories?: string[];
  tax_code?: string;
  size_cat?: string;
  shipping_restrictions?: string;
  case_qty?: number;
}

interface FieldOption {
  label: string;
  value: string;
  type?: number;
  level?: number;
  hexColor?: string;
}

interface FieldOptions {
  companies: FieldOption[];
  artists: FieldOption[];
  sizes: FieldOption[];
  themes: FieldOption[];
  categories: FieldOption[];
  colors: FieldOption[];
  suppliers: FieldOption[];
  taxCategories: FieldOption[];
  shippingRestrictions: FieldOption[];
}


// Add sorting types
type SortDirection = 'asc' | 'desc' | null;
type SortField = 'title' | 'brand' | 'line' | 'price' | 'total_sold' | 'first_received' | 'date_last_sold' | null;

// Date filter options
const DATE_FILTER_OPTIONS = [
  { label: "Any Time", value: "none" },
  { label: "Last week", value: "1week" },
  { label: "Last month", value: "1month" },
  { label: "Last 2 months", value: "2months" },
  { label: "Last 3 months", value: "3months" },
  { label: "Last 6 months", value: "6months" },
  { label: "Last year", value: "1year" }
];

// Create a memoized search component to prevent unnecessary re-renders
const SearchInput = React.memo(({ 
  searchTerm, 
  setSearchTerm, 
  handleSearch, 
  isLoading,
  onClear
}: { 
  searchTerm: string;
  setSearchTerm: (term: string) => void;
  handleSearch: () => void;
  isLoading: boolean;
  onClear: () => void;
}) => {
  // Use local state to buffer updates
  const [localTerm, setLocalTerm] = useState(searchTerm);
  
  // Keep local state in sync with props
  useEffect(() => {
    setLocalTerm(searchTerm);
  }, [searchTerm]);
  
  // Only update parent state when submission happens
  const handleSubmit = (e: React.FormEvent) => { 
    e.preventDefault(); 
    if (localTerm !== searchTerm) {
      setSearchTerm(localTerm);
    }
    handleSearch(); 
  };
  
  // Handle Enter key press
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      if (localTerm !== searchTerm) {
        setSearchTerm(localTerm);
      }
      handleSearch();
    }
  };
  
  return (
    <form onSubmit={handleSubmit} className="flex items-center space-x-2">
      <div className="relative flex-1">
        <Input
          placeholder="Search..."
          value={localTerm}
          onChange={(e) => setLocalTerm(e.target.value)}
          onKeyDown={handleKeyDown}
          className="pr-8"
        />
        {localTerm && (
          <Button
            type="button"
            variant="ghost"
            size="icon"
            className="absolute right-0 top-0 h-full w-8 p-0"
            onClick={() => {
              setLocalTerm('');
              onClear();
            }}
          >
            <X className="h-4 w-4" />
          </Button>
        )}
      </div>
      <Button type="submit" disabled={isLoading}>
        {isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Search className="h-4 w-4" />}
      </Button>
    </form>
  );
});

// Create a memoized filter component
const FilterSelects = React.memo(({ 
  selectedCompany,
  setSelectedCompany,
  selectedDateFilter,
  setSelectedDateFilter,
  companies}: {
  selectedCompany: string;
  setSelectedCompany: (value: string) => void;
  selectedDateFilter: string;
  setSelectedDateFilter: (value: string) => void;
  companies: FieldOption[];
  onFilterChange: (type: string, value: string) => void;
}) => {
  // Forward these to the parent component's updateSearchParams function
  const handleCompanyChange = (value: string) => {
    setSelectedCompany(value);
  };

  const handleDateFilterChange = (value: string) => {
    setSelectedDateFilter(value);
  };

  return (
    <div className="grid grid-cols-2 gap-4">
      <div>
        <Label htmlFor="company-filter" className="text-sm">Filter by Company</Label>
        <Select 
          value={selectedCompany} 
          onValueChange={handleCompanyChange}
        >
          <SelectTrigger id="company-filter">
            <SelectValue placeholder="Any Company" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Any Company</SelectItem>
            {companies.map((company) => (
              <SelectItem key={company.value} value={company.value}>
                {company.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      
      <div>
        <Label htmlFor="date-filter" className="text-sm">Filter by Date</Label>
        <Select 
          value={selectedDateFilter} 
          onValueChange={handleDateFilterChange}
        >
          <SelectTrigger id="date-filter">
            <SelectValue placeholder="Any Time" />
          </SelectTrigger>
          <SelectContent>
            {DATE_FILTER_OPTIONS.map((filter) => (
              <SelectItem key={filter.value} value={filter.value}>
                {filter.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    </div>
  );
});

// Create a memoized results table component

export function SearchProductTemplateDialog({ isOpen, onClose, onTemplateCreated }: ProductSearchDialogProps) {
  // Basic component state
  const [searchResults, setSearchResults] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [step, setStep] = useState<'search' | 'form'>('search');
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [fieldOptions, setFieldOptions] = useState<FieldOptions | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const productsPerPage = 500;
  const [hasSearched, setHasSearched] = useState(false);
  
  // Consolidated search parameters state
  const [searchParams, setSearchParams] = useState({
    searchTerm: '',
    company: 'all',
    dateFilter: 'none'
  });
  
  // Sorting states
  const [sortField, setSortField] = useState<SortField>(null);
  const [sortDirection, setSortDirection] = useState<SortDirection>(null);

  // Debug log for selectedProduct values
  React.useEffect(() => {
    if (selectedProduct) {
      console.log('Selected Product Details:', {
        tax_code: selectedProduct.tax_code,
        size_cat: selectedProduct.size_cat,
        shipping_restrictions: selectedProduct.shipping_restrictions
      });
    }
  }, [selectedProduct]);

  // Simple helper function to check if any filters are active
  const hasActiveFilters = () => {
    return searchParams.company !== 'all' || searchParams.dateFilter !== 'none';
  };

  // Central function to update search parameters
  const updateSearchParams = (newParams: Partial<typeof searchParams>, shouldSearch = true) => {
    // Create updated parameters object
    const updatedParams = { ...searchParams, ...newParams };
    
    // First update the state synchronously
    setSearchParams(updatedParams);
    
    // If we should trigger a search, do it in the next microtask
    // to ensure state updates have been processed
    if (shouldSearch) {
      // Use a local copy of the params to ensure consistency
      queueMicrotask(() => {
        performSearch(updatedParams);
      });
    }
  };

  // Core search function
  const performSearch = async (params: typeof searchParams = searchParams) => {
    setIsLoading(true);
    
    // Use the provided params or the current state
    const searchParamsToUse = params || searchParams;
    
    const hasSearchTerm = searchParamsToUse.searchTerm.trim().length > 0;
    const hasFilters = searchParamsToUse.company !== 'all' || searchParamsToUse.dateFilter !== 'none';
    
    // Update search state
    setHasSearched(hasSearchTerm || hasFilters);
    
    // If no search parameters, reset results
    if (!hasSearchTerm && !hasFilters) {
      setSearchResults([]);
      setHasSearched(false);
      setIsLoading(false);
      return;
    }

    try {
      const apiParams: Record<string, any> = {};
      
      // Add search term if it exists
      if (hasSearchTerm) {
        apiParams.q = searchParamsToUse.searchTerm.trim();
      }
      
      // Add filters if selected
      if (searchParamsToUse.company !== 'all') {
        apiParams.company = searchParamsToUse.company;
      }
      
      if (searchParamsToUse.dateFilter !== 'none') {
        apiParams.dateRange = searchParamsToUse.dateFilter;
      }

      // If we only have filters (no search term), use wildcard search
      if (!hasSearchTerm && hasFilters) {
        apiParams.q = '*';
      }

      const response = await apiClient.get('/api/import/search-products', { params: apiParams });

      setSearchResults(response.data.map((product: Product) => ({
        ...product,
        pid: typeof product.pid === 'string' ? parseInt(product.pid, 10) : product.pid,
        price: typeof product.price === 'string' ? parseFloat(product.price) : product.price,
      })));
    } catch (error) {
      console.error('Error searching products:', error);
      toast.error('Failed to search products', {
        description: 'Could not retrieve search results from the server'
      });
      setSearchResults([]);
    } finally {
      setIsLoading(false);
    }
  };

  // Handler functions
  const handleSearch = () => {
    performSearch();
  };

  const clearSearch = () => {
    updateSearchParams({ searchTerm: '' });
  };

  const clearFilters = () => {
    // One call to updateSearchParams with all filter changes
    // This ensures all filters are cleared in a single atomic update
    updateSearchParams({
      company: 'all',
      dateFilter: 'none'
    });
  };

  // Reset all search state when dialog is closed
  useEffect(() => {
    if (!isOpen) {
      setSearchParams({
        searchTerm: '',
        company: 'all',
        dateFilter: 'none'
      });
      setSearchResults([]);
      setSortField(null);
      setSortDirection(null);
      setCurrentPage(1);
      setStep('search');
      setHasSearched(false);
      setSelectedProduct(null);
    } else {
      // Fetch field options when dialog opens
      fetchFieldOptions();
    }
  }, [isOpen]);

  // Fetch field options when component mounts
  useEffect(() => {
    if (isOpen) {
      fetchFieldOptions();
    }
  }, [isOpen]);

  const fetchFieldOptions = async () => {
    try {
      const response = await apiClient.get('/api/import/field-options');
      setFieldOptions(response.data);
    } catch (error) {
      console.error('Error fetching field options:', error);
      toast.error('Failed to fetch field options', {
        description: 'Could not retrieve field options from the server'
      });
    }
  };

  const handleProductSelect = async (product: Product) => {
    console.log('Selected product from list:', {
      pid: product.pid,
      tax_code: product.tax_code,
      tax_code_type: typeof product.tax_code,
      tax_code_value: `Value: '${product.tax_code}'`,
      size_cat: product.size_cat,
      shipping_restrictions: product.shipping_restrictions,
      case_qty: product.case_qty
    });
    
    setSelectedProduct(product);
    
    // Try to find a matching company ID
    if (product.brand_id && fieldOptions?.companies) {
      // Attempt to match by brand ID
      const companyMatch = fieldOptions.companies.find(c => c.value === product.brand_id);
      if (companyMatch) {
      }
    }
    
    // Fetch product categories if pid is available
    if (product.pid) {
      try {
        const response = await apiClient.get(`/api/import/product-categories/${product.pid}`);
        const productCategories = response.data;
        
        // Update the selected product with the categories
        setSelectedProduct(prev => ({
          ...prev!,
          categories: productCategories.map((cat: any) => cat.value)
        }));
      } catch (error) {
        console.error('Error fetching product categories:', error);
        toast.error('Failed to fetch product categories', {
          description: 'Could not retrieve categories for this product'
        });
      }
    }
    
    setStep('form');
  };

  // Get current products for pagination
  const totalPages = Math.ceil(searchResults.length / productsPerPage);

  // Change page
  const paginate = (pageNumber: number) => setCurrentPage(pageNumber);

  // Generate page numbers for pagination
  const getPageNumbers = () => {
    const pageNumbers = [];
    const maxPagesToShow = 5;
    
    if (totalPages <= maxPagesToShow) {
      // If we have fewer pages than the max to show, display all pages
      for (let i = 1; i <= totalPages; i++) {
        pageNumbers.push(i);
      }
    } else {
      // Always include first page
      pageNumbers.push(1);
      
      // Calculate start and end of middle pages
      let startPage = Math.max(2, currentPage - 1);
      let endPage = Math.min(totalPages - 1, currentPage + 1);
      
      // Adjust if we're near the beginning
      if (currentPage <= 3) {
        endPage = Math.min(totalPages - 1, 4);
      }
      
      // Adjust if we're near the end
      if (currentPage >= totalPages - 2) {
        startPage = Math.max(2, totalPages - 3);
      }
      
      // Add ellipsis after first page if needed
      if (startPage > 2) {
        pageNumbers.push('ellipsis-start');
      }
      
      // Add middle pages
      for (let i = startPage; i <= endPage; i++) {
        pageNumbers.push(i);
      }
      
      // Add ellipsis before last page if needed
      if (endPage < totalPages - 1) {
        pageNumbers.push('ellipsis-end');
      }
      
      // Always include last page
      pageNumbers.push(totalPages);
    }
    
    return pageNumbers;
  };

  // Sort function
  const toggleSort = (field: SortField) => {
    if (sortField === field) {
      // Toggle direction if already sorting by this field
      if (sortDirection === 'asc') {
        setSortDirection('desc');
      } else if (sortDirection === 'desc') {
        setSortField(null);
        setSortDirection(null);
      }
    } else {
      // Set new sort field and direction
      setSortField(field);
      setSortDirection('asc');
    }
    
    // Reset to page 1 when sorting changes
    setCurrentPage(1);
  };

  // Apply sorting to results
  const getSortedResults = (results: Product[]) => {
    if (!sortField || !sortDirection) return results;
    
    return [...results].sort((a, b) => {
      let valueA: any;
      let valueB: any;
      
      // Extract the correct field values
      switch (sortField) {
        case 'title':
          valueA = a.title?.toLowerCase() || '';
          valueB = b.title?.toLowerCase() || '';
          break;
        case 'brand':
          valueA = a.brand?.toLowerCase() || '';
          valueB = b.brand?.toLowerCase() || '';
          break;
        case 'line':
          valueA = a.line?.toLowerCase() || '';
          valueB = b.line?.toLowerCase() || '';
          break;
        case 'price':
          valueA = typeof a.price === 'number' ? a.price : parseFloat(String(a.price) || '0');
          valueB = typeof b.price === 'number' ? b.price : parseFloat(String(b.price) || '0');
          break;
        case 'total_sold':
          valueA = typeof a.total_sold === 'number' ? a.total_sold : parseInt(String(a.total_sold) || '0', 10);
          valueB = typeof b.total_sold === 'number' ? b.total_sold : parseInt(String(b.total_sold) || '0', 10);
          break;
        case 'first_received':
          valueA = a.first_received ? new Date(a.first_received).getTime() : 0;
          valueB = b.first_received ? new Date(b.first_received).getTime() : 0;
          break;
        case 'date_last_sold':
          valueA = a.date_last_sold ? new Date(a.date_last_sold).getTime() : 0;
          valueB = b.date_last_sold ? new Date(b.date_last_sold).getTime() : 0;
          break;
        default:
          return 0;
      }
      
      // Compare the values
      if (valueA < valueB) {
        return sortDirection === 'asc' ? -1 : 1;
      }
      if (valueA > valueB) {
        return sortDirection === 'asc' ? 1 : -1;
      }
      return 0;
    });
  };

  // Update getFilteredResults to remove redundant company filtering
  const getFilteredResults = () => {
    if (!searchResults) return [];
    return searchResults;
  };

  const filteredResults = getFilteredResults();
  const sortedResults = getSortedResults(filteredResults);
  
  // Get current products for pagination
  const indexOfLastProductFiltered = currentPage * productsPerPage;
  const indexOfFirstProductFiltered = indexOfLastProductFiltered - productsPerPage;
  const currentProductsFiltered = sortedResults.slice(indexOfFirstProductFiltered, indexOfLastProductFiltered);
  const totalPagesFiltered = Math.ceil(sortedResults.length / productsPerPage);

  // Get sort icon
  const getSortIcon = (field: SortField) => {
    if (sortField !== field) {
      return <ChevronsUpDown className="ml-1 h-3 w-3 opacity-50" />;
    }
    
    return sortDirection === 'asc' 
      ? <ChevronUp className="ml-1 h-3 w-3" />
      : <ChevronDown className="ml-1 h-3 w-3" />;
  };

  // Sortable table header component
  const SortableTableHead = ({ field, children }: { field: SortField, children: React.ReactNode }) => (
    <TableHead 
      className="cursor-pointer hover:bg-muted/50 transition-colors"
      onClick={() => toggleSort(field)}
    >
      <div className="flex items-center">
        {children}
        {getSortIcon(field)}
      </div>
    </TableHead>
  );

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className={`max-h-[95vh] flex flex-col p-6 ${
        step === 'search' 
          ? searchResults.length > 0 
            ? 'max-w-5xl' 
            : 'max-w-2xl'
          : 'max-w-2xl'
      }`}>
        {step === 'search' ? (
          <>
            <DialogHeader className="px-0">
              <DialogTitle>Search Products</DialogTitle>
              <DialogDescription>
                Search for a product you want to use as a template.
              </DialogDescription>
            </DialogHeader>
            
            <div className="flex-1 overflow-hidden py-4 px-1">
              <div className="flex flex-col gap-4">
                <SearchInput
                  searchTerm={searchParams.searchTerm}
                  setSearchTerm={(term) => updateSearchParams({ searchTerm: term }, false)}
                  handleSearch={handleSearch}
                  isLoading={isLoading}
                  onClear={clearSearch}
                />
                
                <FilterSelects
                  selectedCompany={searchParams.company}
                  setSelectedCompany={(value) => updateSearchParams({ company: value })}
                  selectedDateFilter={searchParams.dateFilter}
                  setSelectedDateFilter={(value) => updateSearchParams({ dateFilter: value })}
                  companies={fieldOptions?.companies || []}
                  onFilterChange={() => {}}
                />
                
                {fieldOptions && hasActiveFilters() && (
                  <div className="flex gap-2">
                    <div className="text-sm text-muted-foreground">Active filters:</div>
                    <div className="flex flex-wrap gap-2">
                      {searchParams.company !== 'all' && (
                        <Badge variant="secondary" className="flex items-center gap-1">
                          Company: {fieldOptions?.companies?.find(c => c.value === searchParams.company)?.label || 'Unknown'}
                          <Button 
                            variant="ghost" 
                            size="icon" 
                            className="h-4 w-4 p-0 ml-1" 
                            onClick={() => {
                              updateSearchParams({ company: 'all' });
                            }}
                          >
                            <X className="h-3 w-3" />
                          </Button>
                        </Badge>
                      )}
                      {searchParams.dateFilter !== 'none' && (
                        <Badge variant="secondary" className="flex items-center gap-1">
                          Date: {(() => {
                            const selectedOption = DATE_FILTER_OPTIONS.find(o => o.value === searchParams.dateFilter);
                            return selectedOption ? selectedOption.label : 'Custom range';
                          })()}
                          <Button 
                            variant="ghost" 
                            size="icon" 
                            className="h-4 w-4 p-0 ml-1" 
                            onClick={() => {
                              updateSearchParams({ dateFilter: 'none' });
                            }}
                          >
                            <X className="h-3 w-3" />
                          </Button>
                        </Badge>
                      )}
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        className="h-6 text-xs" 
                        onClick={clearFilters}
                      >
                        Clear All
                      </Button>
                    </div>
                  </div>
                )}
              </div>
              
              <div className="mt-4">
                <ScrollArea className="flex-1 -mr-6 pr-6 overflow-y-auto max-h-[60vh]">
                  {isLoading ? (
                    <div className="text-center py-4 text-muted-foreground flex items-center justify-center gap-2">
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span>Searching...</span>
                    </div>
                  ) : !hasSearched ? (
                    <div className="text-center py-4 text-muted-foreground">
                      Use the search field or filters to find products
                    </div>
                  ) : searchResults.length === 0 ? (
                    <div className="text-center py-4 text-muted-foreground">
                      No products found matching your criteria
                    </div>
                  ) : (
                    <>
                      <div className="text-sm text-muted-foreground mb-2">
                        {sortedResults.length} products found
                      </div>
                      <div className="relative">
                        <Table>
                          <TableHeader className="sticky top-0 bg-background z-10 border-b">
                            <TableRow>
                              <SortableTableHead field="title">Name</SortableTableHead>
                              {searchParams.company === 'all' && (
                                <SortableTableHead field="brand">Company</SortableTableHead>
                              )}
                              <SortableTableHead field="line">Line</SortableTableHead>
                              <SortableTableHead field="price">Price</SortableTableHead>
                              <SortableTableHead field="total_sold">Total Sold</SortableTableHead>
                              <SortableTableHead field="first_received">Date In</SortableTableHead>
                              <SortableTableHead field="date_last_sold">Last Sold</SortableTableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {currentProductsFiltered.map((product) => (
                              <TableRow 
                                key={product.pid}
                                className="cursor-pointer"
                                onClick={() => handleProductSelect(product)}
                              >
                                <TableCell className="font-medium">{product.title}</TableCell>
                                {searchParams.company === 'all' && (
                                  <TableCell>{product.brand || '-'}</TableCell>
                                )}
                                <TableCell>{product.line || '-'}</TableCell>
                                <TableCell>
                                  {product.price !== null && product.price !== undefined
                                    ? `$${typeof product.price === 'number' 
                                        ? product.price.toFixed(2) 
                                        : parseFloat(String(product.price)).toFixed(2)}`
                                    : '-'}
                                </TableCell>
                                <TableCell>
                                  {product.total_sold !== null && product.total_sold !== undefined
                                    ? typeof product.total_sold === 'number'
                                      ? product.total_sold
                                      : parseInt(String(product.total_sold), 10)
                                    : 0}
                                </TableCell>
                                <TableCell>
                                  {product.first_received 
                                    ? (() => {
                                        try {
                                          return new Date(product.first_received).toLocaleDateString();
                                        } catch (e) {
                                          console.error('Error formatting first_received date:', e);
                                          return '-';
                                        }
                                      })()
                                    : '-'}
                                </TableCell>
                                <TableCell>
                                  {product.date_last_sold 
                                    ? (() => {
                                        try {
                                          return new Date(product.date_last_sold).toLocaleDateString();
                                        } catch (e) {
                                          console.error('Error formatting date_last_sold date:', e);
                                          return '-';
                                        }
                                      })()
                                    : '-'}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                      
                      {totalPagesFiltered > 1 && (
                        <div className="mt-4">
                          <Pagination>
                            <PaginationContent>
                              <PaginationItem>
                                <PaginationPrevious 
                                  onClick={() => currentPage > 1 && paginate(currentPage - 1)}
                                  className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
                                />
                              </PaginationItem>
                              
                              {getPageNumbers().map((page, index) => (
                                <PaginationItem key={index}>
                                  {page === 'ellipsis-start' || page === 'ellipsis-end' ? (
                                    <PaginationEllipsis />
                                  ) : (
                                    <PaginationLink
                                      isActive={page === currentPage}
                                      onClick={() => typeof page === 'number' && paginate(page)}
                                      className={typeof page === 'number' ? "cursor-pointer" : ""}
                                    >
                                      {page}
                                    </PaginationLink>
                                  )}
                                </PaginationItem>
                              ))}
                              
                              <PaginationItem>
                                <PaginationNext 
                                  onClick={() => currentPage < totalPagesFiltered && paginate(currentPage + 1)}
                                  className={currentPage === totalPagesFiltered ? "pointer-events-none opacity-50" : "cursor-pointer"}
                                />
                              </PaginationItem>
                            </PaginationContent>
                          </Pagination>
                        </div>
                      )}
                    </>
                  )}
                </ScrollArea>
              </div>
            </div>
            
            <DialogFooter className="px-0 mt-6">
              <Button variant="outline" onClick={onClose}>Cancel</Button>
            </DialogFooter>
          </>
        ) : (
          <TemplateForm
            isOpen={true}
            onClose={() => setStep('search')}
            onSuccess={onTemplateCreated}
            initialData={selectedProduct ? (() => {
              console.log('Creating TemplateForm initialData with tax_code:', selectedProduct.tax_code);
              return {
                company: selectedProduct.brand_id,
                product_type: '',
                supplier: selectedProduct.supplier,
                msrp: selectedProduct.regular_price ? Number(Number(selectedProduct.regular_price).toFixed(2)) : undefined,
                cost_each: selectedProduct.cost_price ? Number(Number(selectedProduct.cost_price).toFixed(2)) : undefined,
                qty_per_unit: selectedProduct.moq ? Number(selectedProduct.moq) : undefined,
                case_qty: selectedProduct.case_qty ? Number(selectedProduct.case_qty) : undefined,
                hts_code: selectedProduct.harmonized_tariff_code || undefined,
                description: selectedProduct.description || undefined,
                weight: selectedProduct.weight ? Number(Number(selectedProduct.weight).toFixed(2)) : undefined,
                length: selectedProduct.length ? Number(Number(selectedProduct.length).toFixed(2)) : undefined,
                width: selectedProduct.width ? Number(Number(selectedProduct.width).toFixed(2)) : undefined,
                height: selectedProduct.height ? Number(Number(selectedProduct.height).toFixed(2)) : undefined,
                categories: selectedProduct.categories || [],
                tax_cat: selectedProduct.tax_code ? String(selectedProduct.tax_code) : undefined,
                size_cat: selectedProduct.size_cat ? String(selectedProduct.size_cat) : undefined,
                ship_restrictions: selectedProduct.shipping_restrictions ? [String(selectedProduct.shipping_restrictions)] : undefined
              };
            })() : null}
            mode="create"
            fieldOptions={fieldOptions}
          />
        )}
      </DialogContent>
    </Dialog>
  );
} 