import React, { useState, useRef, useEffect } from 'react';
import { ChevronDown, X } from 'lucide-react';

export interface Option {
    id: number;
    title: string;
    description?: string;
}

interface MultiSelectAutocompleteProps {
    options: Option[];
    selectedValues: number[];
    onChange: (values: number[]) => void;
    placeholder?: string;
    label?: string;
    error?: string;
    isLoading?: boolean;
    disabled?: boolean;
    onSearchChange?: (query: string) => void;
    onLoadMore?: () => void;
    hasMore?: boolean;
    loadingMore?: boolean;
}

export const MultiSelectAutocomplete: React.FC<MultiSelectAutocompleteProps> = ({
    options,
    selectedValues,
    onChange,
    placeholder = "انتخاب کنید...",
    label,
    error,
    isLoading = false,
    disabled = false,
    onSearchChange,
    onLoadMore,
    hasMore = false,
    loadingMore = false,
}) => {
    const [isOpen, setIsOpen] = useState(false);
    const [searchTerm, setSearchTerm] = useState('');
    const dropdownRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);
    const listRef = useRef<HTMLDivElement>(null);

    const filteredOptions = options.filter(option =>
        option.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (option.description && option.description.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    // If parent provides onSearchChange, assume server-side filtering and use options as-is
    const displayedOptions = onSearchChange ? options : filteredOptions;

    const selectedOptions = options.filter(option => selectedValues.includes(option.id));

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false);
                setSearchTerm('');
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleToggleOption = (optionId: number) => {
        if (selectedValues.includes(optionId)) {
            onChange(selectedValues.filter(id => id !== optionId));
        } else {
            onChange([...selectedValues, optionId]);
        }
    };

    const handleRemoveOption = (optionId: number) => {
        onChange(selectedValues.filter(id => id !== optionId));
    };

    const handleToggleDropdown = () => {
        if (disabled) return;
        setIsOpen(!isOpen);
        if (!isOpen) {
            setTimeout(() => inputRef.current?.focus(), 100);
        }
    };

    return (
        <div className="relative" ref={dropdownRef}>
            {label && (
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {label}
                </label>
            )}

            {/* Selected Items Display */}
            <div
                className={`
                    w-full px-3 py-3 text-base border rounded-lg 
                    focus-within:outline-none focus-within:ring-2 focus-within:ring-primary-500 
                    cursor-pointer transition-all duration-200
                    ${error ? 'border-red-300 focus-within:border-red-500 focus-within:ring-red-500' : 'border-gray-300 dark:border-gray-600 focus-within:border-primary-500'}
                    ${disabled ? 'bg-gray-100 cursor-not-allowed' : 'bg-white dark:bg-gray-700'}
                    dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400
                `}
                onClick={handleToggleDropdown}
            >
                <div className="flex flex-wrap gap-1 items-center">
                    {selectedOptions.length > 0 ? (
                        selectedOptions.map(option => (
                            <span
                                key={option.id}
                                className="inline-flex items-center gap-1 px-2 py-1 bg-primary-100 dark:bg-primary-800 text-primary-800 dark:text-primary-100 text-xs rounded-md"
                            >
                                {option.title || option.description || `#${option.id}`}
                                <button
                                    type="button"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        handleRemoveOption(option.id);
                                    }}
                                    className="hover:bg-primary-200 dark:hover:bg-primary-700 rounded-full p-0.5 transition-colors"
                                    disabled={disabled}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </span>
                        ))
                    ) : (
                        <span className="text-gray-500 dark:text-gray-400">{placeholder}</span>
                    )}

                    <div className="flex-1 min-w-[60px]">

                        {isOpen && !disabled && (
                            <input
                                ref={inputRef}
                                type="text"
                                value={searchTerm}
                                onChange={(e) => {
                                    const value = e.target.value;
                                    setSearchTerm(value);
                                    if (onSearchChange) onSearchChange(value);
                                }}
                                className="w-full border-none outline-none bg-transparent text-sm"
                                placeholder="جستجو..."
                            />
                        )}
                    </div>

                    <ChevronDown
                        className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
                    />
                </div>
            </div>

            {/* Dropdown */}
            {isOpen && !disabled && (
                <div
                    ref={listRef}
                    onScroll={() => {
                        const el = listRef.current;
                        if (!el || !onLoadMore || !hasMore || loadingMore) return;
                        const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 24;
                        if (nearBottom) onLoadMore();
                    }}
                    className="absolute z-50 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg max-h-60 overflow-auto"
                >
                    {isLoading ? (
                        <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                            در حال بارگذاری...
                        </div>
                    ) : displayedOptions.length > 0 ? (
                        <>
                            {displayedOptions.map(option => (
                                <div
                                    key={option.id}
                                    className={`
                  px-3 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700
                  ${selectedValues.includes(option.id) ? 'bg-primary-200 dark:bg-primary-700/70' : ''}
                `}
                                    onClick={() => handleToggleOption(option.id)}
                                >
                                    <div className="flex items-center justify-between">
                                        <div>
                                            <div className="text-sm font-medium text-gray-900 dark:text-gray-100">
                                                {option.title}
                                            </div>
                                            {option.description && (
                                                <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                                    {option.description}
                                                </div>
                                            )}
                                        </div>
                                        {selectedValues.includes(option.id) && (
                                            <div className="text-primary-600 dark:text-primary-400">✓</div>
                                        )}
                                    </div>
                                </div>
                            ))}
                            {onLoadMore && hasMore && (
                                <div className="p-2 text-center text-xs text-gray-500 dark:text-gray-400">
                                    {loadingMore ? 'در حال بارگذاری بیشتر...' : 'اسکرول برای مشاهده بیشتر'}
                                </div>
                            )}
                        </>
                    ) : (
                        <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                            موردی یافت نشد
                        </div>
                    )}
                </div>
            )}

            {error && (
                <p className="mt-1 text-sm text-red-600 dark:text-red-400">{error}</p>
            )}
        </div>
    );
}; 