import React, { useState, useEffect } from 'react';
import api from '../utils/api';

const ProductSelector = ({ selectedProducts = [], onChange, label, description, currentProductId }) => {
    const [products, setProducts] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');
    const [loading, setLoading] = useState(false);
    const [showDropdown, setShowDropdown] = useState(false);

    useEffect(() => {
        if (searchTerm.length >= 2) {
            searchProducts();
        } else {
            setProducts([]);
            setShowDropdown(false);
        }
    }, [searchTerm]);

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (showDropdown && !e.target.closest('.search-wrapper')) {
                setShowDropdown(false);
            }
        };
        
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [showDropdown]);

    const searchProducts = async () => {
        try {
            setLoading(true);
            const response = await api.getProducts({ search: searchTerm, per_page: 20 });
            if (response.success) {
                // Filter out current product and already selected products
                const filtered = (response.products || []).filter(p => 
                    p.id !== currentProductId && 
                    !selectedProducts.some(sp => sp.id === p.id)
                );
                setProducts(filtered);
            }
        } catch (error) {
            console.error('Error searching products:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleSelectProduct = (product) => {
        onChange([...selectedProducts, { id: product.id, name: product.name }]);
        setSearchTerm('');
        setProducts([]);
        setShowDropdown(false);
    };

    const handleRemoveProduct = (productId) => {
        onChange(selectedProducts.filter(p => p.id !== productId));
    };

    return (
        <div className="product-selector">
            <label>{label}</label>
            {description && <p className="field-description">{description}</p>}
            
            {/* Selected Products */}
            {selectedProducts.length > 0 && (
                <div className="selected-products">
                    {selectedProducts.map(product => (
                        <div key={product.id} className="selected-product-item">
                            <span>{product.name}</span>
                            <button
                                type="button"
                                onClick={() => handleRemoveProduct(product.id)}
                                className="btn-remove"
                            >
                                ✕
                            </button>
                        </div>
                    ))}
                </div>
            )}

            {/* Search Input */}
            <div className="search-wrapper" style={{ position: 'relative' }}>
                <input
                    type="text"
                    value={searchTerm}
                    onChange={(e) => {
                        setSearchTerm(e.target.value);
                        setShowDropdown(true);
                    }}
                    onFocus={() => setShowDropdown(true)}
                    placeholder="Search products..."
                />
                
                {/* Search Results Dropdown */}
                {showDropdown && searchTerm.length >= 2 && (
                    <div className="search-dropdown">
                        {loading ? (
                            <div className="dropdown-item">Loading...</div>
                        ) : products.length === 0 ? (
                            <div className="dropdown-item">No products found</div>
                        ) : (
                            products.map(product => (
                                <div
                                    key={product.id}
                                    className="dropdown-item"
                                    onClick={() => handleSelectProduct(product)}
                                >
                                    <div className="product-info">
                                        {product.images && product.images[0] && (
                                            <img 
                                                src={product.images[0].src} 
                                                alt={product.name}
                                                style={{ width: '40px', height: '40px', objectFit: 'cover', borderRadius: '4px' }}
                                            />
                                        )}
                                        <div>
                                            <div className="product-name">{product.name}</div>
                                            <div className="product-price">${product.price}</div>
                                        </div>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                )}
            </div>
        </div>
    );
};

export default ProductSelector;
