import React, { useState, useEffect, useMemo } from 'react'
import { useSearchProducts } from '../pages/products/hooks/useProductData'
import { type ProductListType } from '../pages/products/types/Types'
import MultiSelectSearchable, { type MultiSelectOption } from './MultiSelectSearchable'

type ProductMultiSelectProps = {
    value: number[]
    onChange: (value: number[]) => void
    placeholder?: string
    label?: string
    error_text?: string
    disabled?: boolean
}

const ProductMultiSelect: React.FC<ProductMultiSelectProps> = ({
    value,
    onChange,
    placeholder = "انتخاب محصولات...",
    label,
    error_text,
    disabled = false,
}) => {
    const [searchTerm, setSearchTerm] = useState('')
    const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('')
    const [selectedProducts, setSelectedProducts] = useState<ProductListType[]>([])
    const [dropdownOpen, setDropdownOpen] = useState(false)

    // Debounce search term
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedSearchTerm(searchTerm)
        }, 300)

        return () => clearTimeout(timer)
    }, [searchTerm])

    // Search products (includes initial load and search)
    const { data: searchResults, isLoading } = useSearchProducts(debouncedSearchTerm, true)

    // Combine selected products with search results
    const allProducts = useMemo(() => {
        const productsMap = new Map<string, ProductListType>()

        // Add selected products
        selectedProducts.forEach(product => {
            productsMap.set(product._id.toString(), product)
        })

        // Add search results
        if (searchResults?.results?.products) {
            searchResults.results.products.forEach((product: ProductListType) => {
                productsMap.set(product._id.toString(), product)
            })
        }

        return Array.from(productsMap.values())
    }, [selectedProducts, searchResults])

    // Convert to options format
    const options: MultiSelectOption[] = useMemo(() => {
        return allProducts.map(product => ({
            value: product._id.toString(),
            label: product.title_fa || product.title_en
        }))
    }, [allProducts])

    const handleChange = (newValue: string[]) => {
        // Update selected products list
        const newSelectedProducts = allProducts.filter(product =>
            newValue.includes(product._id.toString())
        )
        setSelectedProducts(newSelectedProducts)

        // Convert back to numbers for the parent component
        onChange(newValue.map(v => parseInt(v)))
    }

    // Custom search handler for MultiSelectSearchable
    const handleSearch = (term: string) => {
        setSearchTerm(term)
    }

    return (
        <div className="w-full">
            {label && (
                <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 block mb-1">
                    {label}
                </label>
            )}

            <MultiSelectSearchable
                options={options}
                value={value.map(v => v.toString())}
                onChange={handleChange}
                onSearch={handleSearch}
                onOpenChange={setDropdownOpen}
                placeholder={placeholder}
                error_text={error_text}
                disabled={disabled}
                loading={isLoading}
            />

            {dropdownOpen && !isLoading && allProducts.length === 0 && (
                <div className="text-xs text-muted-foreground mt-1">
                    {searchTerm ? 'محصولی یافت نشد.' : 'برای جستجو نام محصول را تایپ کنید.'}
                </div>
            )}
        </div>
    )
}

export default ProductMultiSelect
