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

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

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

export const SingleSelectAutocomplete: React.FC<SingleSelectAutocompleteProps> = ({
    options,
    selectedValue,
    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()))
    );

    const displayedOptions = onSearchChange ? options : filteredOptions;
    const selectedOption = options.find(option => option.id === selectedValue);

    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 handleSelectOption = (optionId: number) => {
        onChange(optionId);
        setIsOpen(false);
        setSearchTerm('');
    };

    const handleClearSelection = (e: React.MouseEvent) => {
        e.stopPropagation();
        onChange(undefined);
    };

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

    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        setSearchTerm(value);
        if (onSearchChange) {
            onSearchChange(value);
        }
    };

    const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
        const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
        if (scrollHeight - scrollTop <= clientHeight + 5 && hasMore && !loadingMore && onLoadMore) {
            onLoadMore();
        }
    };

    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>
            )}

            <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 items-center justify-between">
                    <div className="flex-1">
                        {selectedOption ? (
                            <div className="flex items-center justify-between">
                                <div>
                                    <span className="text-sm font-medium">{selectedOption.title}</span>
                                    {selectedOption.description && (
                                        <span className="text-xs text-gray-500 dark:text-gray-400 block">
                                            {selectedOption.description}
                                        </span>
                                    )}
                                </div>
                                <button
                                    type="button"
                                    onClick={handleClearSelection}
                                    className="ml-2 p-1 hover:bg-gray-200 dark:hover:bg-gray-600 rounded"
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </div>
                        ) : (
                            <span className="text-gray-500 dark:text-gray-400">{placeholder}</span>
                        )}
                    </div>
                    <ChevronDown className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
                </div>
            </div>

            {isOpen && (
                <div className="absolute z-50 w-full mt-1 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg">
                    <div className="p-2 border-b border-gray-200 dark:border-gray-600">
                        <input
                            ref={inputRef}
                            type="text"
                            value={searchTerm}
                            onChange={handleSearchChange}
                            placeholder="جستجو..."
                            className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-1 focus:ring-primary-500 dark:bg-gray-600 dark:text-gray-100"
                        />
                    </div>

                    <div
                        ref={listRef}
                        className="max-h-60 overflow-y-auto"
                        onScroll={handleScroll}
                    >
                        {isLoading && displayedOptions.length === 0 ? (
                            <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                                در حال بارگذاری...
                            </div>
                        ) : displayedOptions.length === 0 ? (
                            <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                                موردی یافت نشد
                            </div>
                        ) : (
                            <>
                                {displayedOptions.map((option) => (
                                    <div
                                        key={option.id}
                                        className={`
                                            p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-600 
                                            ${selectedValue === option.id ? 'bg-blue-50 dark:bg-blue-900' : ''}
                                        `}
                                        onClick={() => handleSelectOption(option.id)}
                                    >
                                        <div className="font-medium text-sm">{option.title}</div>
                                        {option.description && (
                                            <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                                {option.description}
                                            </div>
                                        )}
                                    </div>
                                ))}
                                {loadingMore && (
                                    <div className="p-3 text-center text-gray-500 dark:text-gray-400">
                                        در حال بارگذاری بیشتر...
                                    </div>
                                )}
                            </>
                        )}
                    </div>
                </div>
            )}

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