import {
    useEffect,
    useId,
    useMemo,
    useRef,
    useState,
    type KeyboardEvent,
} from 'react';
import { CheckIcon, ChevronDownIcon, SearchIcon } from '@/components/Icons';
import { cn } from '@/lib/utils';

export interface SelectOption {
    value: string;
    label: string;
    description?: string;
    disabled?: boolean;
}

interface SelectProps {
    value: string;
    onChange: (value: string) => void;
    options: SelectOption[];
    placeholder?: string;
    variant?: 'form' | 'filter';
    size?: 'md' | 'sm';
    searchable?: boolean;
    searchPlaceholder?: string;
    disabled?: boolean;
    className?: string;
    id?: string;
    name?: string;
    'aria-label'?: string;
}

export default function Select({
    value,
    onChange,
    options,
    placeholder = 'انتخاب کنید...',
    variant = 'form',
    size = 'md',
    searchable,
    searchPlaceholder = 'جستجو...',
    disabled = false,
    className,
    id,
    name,
    'aria-label': ariaLabel,
}: SelectProps) {
    const generatedId = useId();
    const listboxId = `${id ?? generatedId}-listbox`;
    const containerRef = useRef<HTMLDivElement>(null);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const searchInputRef = useRef<HTMLInputElement>(null);
    const listRef = useRef<HTMLUListElement>(null);

    const [open, setOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const [highlightedIndex, setHighlightedIndex] = useState(-1);
    const [alignSide, setAlignSide] = useState<'right' | 'left'>('right');

    const showSearch = searchable ?? options.length > 8;

    const selectedOption = useMemo(
        () => options.find((opt) => opt.value === value),
        [options, value],
    );

    const filteredOptions = useMemo(() => {
        const query = searchQuery.trim().toLowerCase();
        if (!query) {
            return options;
        }

        return options.filter(
            (opt) =>
                opt.label.toLowerCase().includes(query) ||
                opt.description?.toLowerCase().includes(query),
        );
    }, [options, searchQuery]);

    useEffect(() => {
        if (!open) {
            setSearchQuery('');
            setHighlightedIndex(-1);
            return;
        }

        if (triggerRef.current) {
            const rect = triggerRef.current.getBoundingClientRect();
            const spaceOnLeft = rect.left;
            const spaceOnRight = window.innerWidth - rect.right;
            setAlignSide(spaceOnLeft < spaceOnRight ? 'left' : 'right');
        }

        const currentIdx = filteredOptions.findIndex(
            (opt) => opt.value === value && !opt.disabled,
        );
        setHighlightedIndex(currentIdx >= 0 ? currentIdx : 0);

        if (showSearch) {
            requestAnimationFrame(() => {
                searchInputRef.current?.focus();
            });
        }
    }, [open, showSearch]);

    useEffect(() => {
        if (!open) {
            return;
        }

        function handleClickOutside(event: MouseEvent) {
            if (
                containerRef.current &&
                !containerRef.current.contains(event.target as Node)
            ) {
                setOpen(false);
            }
        }

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

    useEffect(() => {
        if (!open || highlightedIndex < 0 || !listRef.current) {
            return;
        }

        const item = listRef.current.children[highlightedIndex] as
            | HTMLElement
            | undefined;
        item?.scrollIntoView({ block: 'nearest' });
    }, [open, highlightedIndex]);

    function selectOption(option: SelectOption) {
        if (option.disabled) {
            return;
        }
        onChange(option.value);
        setOpen(false);
        triggerRef.current?.focus();
    }

    function moveHighlight(delta: 1 | -1) {
        if (filteredOptions.length === 0) {
            return;
        }

        let next = highlightedIndex;
        for (let i = 0; i < filteredOptions.length; i++) {
            next =
                (next + delta + filteredOptions.length) %
                filteredOptions.length;
            if (!filteredOptions[next].disabled) {
                setHighlightedIndex(next);
                return;
            }
        }
    }

    function handleKeyDown(e: KeyboardEvent) {
        if (disabled) {
            return;
        }

        if (!open) {
            if (
                e.key === 'Enter' ||
                e.key === ' ' ||
                e.key === 'ArrowDown' ||
                e.key === 'ArrowUp'
            ) {
                e.preventDefault();
                setOpen(true);
            }
            return;
        }

        switch (e.key) {
            case 'Escape':
                e.preventDefault();
                setOpen(false);
                triggerRef.current?.focus();
                break;
            case 'ArrowDown':
                e.preventDefault();
                moveHighlight(1);
                break;
            case 'ArrowUp':
                e.preventDefault();
                moveHighlight(-1);
                break;
            case 'Home':
                e.preventDefault();
                setHighlightedIndex(0);
                break;
            case 'End':
                e.preventDefault();
                setHighlightedIndex(filteredOptions.length - 1);
                break;
            case 'Enter':
                e.preventDefault();
                if (
                    highlightedIndex >= 0 &&
                    filteredOptions[highlightedIndex]
                ) {
                    selectOption(filteredOptions[highlightedIndex]);
                }
                break;
            case 'Tab':
                setOpen(false);
                break;
        }
    }

    const isActiveFilter = variant === 'filter' && value !== '';

    return (
        <div
            ref={containerRef}
            onKeyDown={handleKeyDown}
            className={cn('relative', className)}
        >
            {name && <input type="hidden" name={name} value={value} />}

            <button
                ref={triggerRef}
                id={id}
                type="button"
                disabled={disabled}
                aria-haspopup="listbox"
                aria-expanded={open}
                aria-controls={open ? listboxId : undefined}
                aria-label={ariaLabel}
                onClick={() => setOpen((prev) => !prev)}
                className={cn(
                    'flex w-full items-center justify-between gap-2 rounded-xl border text-right transition duration-150 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60',
                    size === 'sm' ? 'h-10 px-3 text-xs' : 'h-11 px-3.5 text-sm',
                    variant === 'filter' &&
                        size === 'md' &&
                        'text-xs font-medium',
                    variant === 'filter' && size === 'sm' && 'font-semibold',
                    isActiveFilter
                        ? 'border-brand-blue/40 bg-blue-50/60 font-semibold text-brand-blue hover:border-brand-blue/60'
                        : variant === 'filter'
                          ? 'border-slate-300 bg-slate-50 text-slate-700 hover:border-slate-400 hover:bg-white'
                          : 'border-slate-300 bg-white text-slate-900 hover:border-slate-400',
                    open &&
                        'border-brand-blue bg-white ring-2 ring-brand-blue/15',
                )}
            >
                <span
                    className={cn(
                        'truncate',
                        !selectedOption && 'text-slate-400',
                    )}
                >
                    {selectedOption ? selectedOption.label : placeholder}
                </span>
                <ChevronDownIcon
                    className={cn(
                        'h-4 w-4 shrink-0 transition-transform duration-200',
                        isActiveFilter ? 'text-brand-blue' : 'text-slate-400',
                        open && 'rotate-180 text-brand-blue',
                    )}
                />
            </button>

            {open && (
                <div
                    className={cn(
                        'absolute top-full z-50 mt-1.5 overflow-hidden rounded-2xl border border-slate-200/90 bg-white p-1.5 shadow-xl ring-1 shadow-slate-900/10 ring-slate-900/5',
                        alignSide === 'left' ? 'left-0' : 'right-0',
                        variant === 'filter'
                            ? 'w-max max-w-[min(20rem,calc(100vw-2rem))] min-w-full'
                            : 'w-full max-w-[calc(100vw-2rem)] min-w-[12rem]',
                    )}
                >
                    {showSearch && (
                        <div className="mb-1.5 border-b border-slate-100 px-1 pb-1.5">
                            <div className="relative">
                                <input
                                    ref={searchInputRef}
                                    type="text"
                                    value={searchQuery}
                                    onChange={(e) => {
                                        setSearchQuery(e.target.value);
                                        setHighlightedIndex(0);
                                    }}
                                    placeholder={searchPlaceholder}
                                    className="h-9 w-full rounded-lg border border-slate-200 bg-slate-50 pr-8 pl-2.5 text-xs text-slate-800 placeholder:text-slate-400 focus:border-brand-blue focus:bg-white focus:outline-none"
                                />
                                <SearchIcon className="pointer-events-none absolute top-2.5 right-2.5 h-4 w-4 text-slate-400" />
                            </div>
                        </div>
                    )}

                    <ul
                        ref={listRef}
                        id={listboxId}
                        role="listbox"
                        className="max-h-60 space-y-0.5 overflow-y-auto overscroll-contain py-0.5"
                    >
                        {filteredOptions.length === 0 ? (
                            <li className="px-3 py-4 text-center text-xs text-slate-400">
                                موردی یافت نشد
                            </li>
                        ) : (
                            filteredOptions.map((option, index) => {
                                const isSelected = option.value === value;
                                const isHighlighted =
                                    index === highlightedIndex;

                                return (
                                    <li
                                        key={option.value || `__empty_${index}`}
                                        role="option"
                                        aria-selected={isSelected}
                                        aria-disabled={option.disabled}
                                        onMouseEnter={() => {
                                            if (!option.disabled) {
                                                setHighlightedIndex(index);
                                            }
                                        }}
                                        onClick={() => selectOption(option)}
                                        className={cn(
                                            'flex cursor-pointer items-center justify-between gap-2.5 rounded-xl px-3 py-2 text-right transition-colors',
                                            size === 'sm' ||
                                                variant === 'filter'
                                                ? 'text-xs'
                                                : 'text-sm',
                                            option.disabled &&
                                                'cursor-not-allowed opacity-45',
                                            isSelected
                                                ? 'bg-blue-50/90 font-semibold text-brand-blue'
                                                : isHighlighted
                                                  ? 'bg-slate-100 text-slate-900'
                                                  : 'text-slate-700 hover:bg-slate-50 hover:text-slate-950',
                                        )}
                                    >
                                        <div className="min-w-0 flex-1">
                                            <div className="truncate">
                                                {option.label}
                                            </div>
                                            {option.description && (
                                                <div className="mt-0.5 truncate text-[11px] font-normal text-slate-500">
                                                    {option.description}
                                                </div>
                                            )}
                                        </div>
                                        {isSelected && (
                                            <CheckIcon className="h-4 w-4 shrink-0 text-brand-blue" />
                                        )}
                                    </li>
                                );
                            })
                        )}
                    </ul>
                </div>
            )}
        </div>
    );
}
