'use client';

import { useState, useEffect, useRef } from 'react';
import { Check, ChevronDown, X, Search } from 'lucide-react';
import { Button } from '@/components/common/button';
import { Input } from '@/components/common/input';
import { Badge } from '@/components/common/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/common/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from '@/components/common/command';
import { ScrollArea } from '@/components/common/scroll-area';
import { Product } from '@/lib/types/promotion';
import { fetchClient } from '@/lib/api';

interface ProductSelectorProps {
  selectedProductIds: string[];
  onSelectionChange: (productIds: string[]) => void;
  placeholder?: string;
  maxHeight?: string;
}

export default function ProductSelector({ 
  selectedProductIds, 
  onSelectionChange, 
  placeholder = "Select products...",
  maxHeight = "200px"
}: ProductSelectorProps) {
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const triggerRef = useRef<HTMLButtonElement>(null);

  // Handle escape key to close dropdown
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && open) {
        setOpen(false);
      }
    };

    if (open) {
      document.addEventListener('keydown', handleKeyDown);
      return () => document.removeEventListener('keydown', handleKeyDown);
    }
  }, [open]);

  // Fetch products when component mounts
  useEffect(() => {
    const fetchProducts = async () => {
      setLoading(true);
      try {
        const response = await fetchClient('/promotions/products/all');
        // Ensure we only set an array to state to avoid runtime errors
        if (Array.isArray(response)) {
          setProducts(response);
        } else if (response && Array.isArray((response as any).products)) {
          setProducts((response as any).products);
        } else {
          console.error('Unexpected products response shape:', response);
          setProducts([]);
        }
      } catch (error) {
        console.error('Error fetching products:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchProducts();
  }, []);

  // Filter products based on search term
  const filteredProducts = products.filter(product =>
    product.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    product.description?.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Get selected products for display
  const selectedProducts = products.filter(product => 
    selectedProductIds.includes(product._id)
  );

  const handleProductToggle = (productId: string) => {
    const updatedSelection = selectedProductIds.includes(productId)
      ? selectedProductIds.filter(id => id !== productId)
      : [...selectedProductIds, productId];
    
    onSelectionChange(updatedSelection);
  };

  const handleRemoveProduct = (productId: string) => {
    onSelectionChange(selectedProductIds.filter(id => id !== productId));
  };

  const clearAll = () => {
    onSelectionChange([]);
  };

  return (
    <div className="space-y-2">
      <div className="relative">
        <Button
          ref={triggerRef}
          type="button"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            setOpen(!open);
          }}
          className="w-full justify-between h-auto min-h-[40px] p-3"
        >
          <div className="flex items-center gap-2 flex-1">
            {selectedProducts.length === 0 ? (
              <span className="text-muted-foreground">{placeholder}</span>
            ) : (
              <span className="text-sm">
                {selectedProducts.length} product{selectedProducts.length !== 1 ? 's' : ''} selected
              </span>
            )}
          </div>
          <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
        
        {/* Dropdown using absolute positioning within relative container */}
        {open && (
          <div 
            className="absolute top-full left-0 right-0 z-50 mt-1 bg-background border border-border rounded-md shadow-lg"
            style={{ minWidth: '300px', maxHeight: '400px' }}
          >
            {/* Search Header */}
            <div className="flex items-center gap-2 p-3 border-b bg-muted/30">
              <Search className="h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search products..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="border-0 bg-transparent p-0 h-auto focus-visible:ring-0 focus-visible:ring-offset-0"
                autoFocus
              />
            </div>
            
            {/* Products List */}
            <ScrollArea className="h-[300px]">
              {loading ? (
                <div className="p-4 text-center text-sm text-muted-foreground">
                  Loading products...
                </div>
              ) : filteredProducts.length === 0 ? (
                <div className="p-4 text-center text-sm text-muted-foreground">
                  {searchTerm ? 'No products found matching your search.' : 'No products found.'}
                </div>
              ) : (
                <div className="p-1">
                  {filteredProducts.map((product) => (
                    <div
                      key={product._id}
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        handleProductToggle(product._id);
                      }}
                      className="flex items-center gap-3 p-2 hover:bg-accent rounded-sm cursor-pointer transition-colors"
                    >
                      <div className={`h-4 w-4 border rounded-sm flex items-center justify-center ${
                        selectedProductIds.includes(product._id)
                          ? 'bg-primary border-primary text-primary-foreground'
                          : 'border-input'
                      }`}>
                        {selectedProductIds.includes(product._id) && (
                          <Check className="h-3 w-3" />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-sm">{product.name}</div>
                        {product.description && (
                          <div className="text-xs text-muted-foreground truncate">
                            {product.description}
                          </div>
                        )}
                      </div>
                      {!product.enabled && (
                        <Badge variant="secondary" className="text-xs">
                          Disabled
                        </Badge>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </ScrollArea>
          </div>
        )}

        {/* Backdrop to close dropdown */}
        {open && (
          <div 
            className="fixed inset-0 z-40" 
            onClick={() => setOpen(false)}
          />
        )}
      </div>

      {/* Selected products display */}
      {selectedProducts.length > 0 && (
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">Selected Products:</span>
            <Button 
              type="button"
              variant="ghost" 
              size="sm" 
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                clearAll();
              }}
              className="h-6 px-2 text-xs"
            >
              Clear All
            </Button>
          </div>
          <div className="flex flex-wrap gap-2">
            {selectedProducts.map((product) => (
              <Badge 
                key={product._id} 
                variant="secondary" 
                className="flex items-center gap-1 pr-1"
              >
                <span className="text-xs">{product.name}</span>
                <button
                  type="button"
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    handleRemoveProduct(product._id);
                  }}
                  className="ml-1 hover:bg-secondary-foreground/20 rounded-full p-0.5"
                >
                  <X className="h-3 w-3" />
                </button>
              </Badge>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

