"use client";

import { useState, useRef, useEffect, Fragment } from 'react';
import { Combobox, Transition } from '@headlessui/react';
import { ChevronUpDownIcon, CheckIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline';

interface Option {
    id: string;
    name: string;
    subtitle?: string;
}

interface SearchableSelectProps {
    options: Option[];
    value: string;
    onChange: (value: string | null) => void;
    placeholder?: string;
    emptyText?: string;
    label?: string;
    helperText?: string;
}

export default function SearchableSelect({
    options,
    value,
    onChange,
    placeholder = 'Selecione...',
    emptyText = 'Nenhum resultado encontrado',
    label,
    helperText,
}: SearchableSelectProps) {
    const [query, setQuery] = useState('');

    const selectedOption = options.find(opt => opt.id === value);

    const filteredOptions =
        query === ''
            ? options
            : options.filter((option) =>
                option.name.toLowerCase().includes(query.toLowerCase()) ||
                option.subtitle?.toLowerCase().includes(query.toLowerCase())
            );

    return (
        <div>
            {label && (
                <label className="block text-sm font-medium text-zinc-700 dark:text-zinc-300 mb-2">
                    {label}
                </label>
            )}
            <Combobox value={value} onChange={onChange}>
                <div className="relative">
                    <div className="relative w-full">
                        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                            <MagnifyingGlassIcon className="w-5 h-5 text-zinc-400" />
                        </div>
                        <Combobox.Input
                            className="w-full pl-10 pr-10 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-lg bg-white dark:bg-zinc-900 text-zinc-900 dark:text-white placeholder-zinc-400 focus:outline-none focus:ring-2 focus:ring-[var(--brand-color)] focus:border-transparent transition-all"
                            displayValue={() => selectedOption ? `${selectedOption.name}${selectedOption.subtitle ? ` (${selectedOption.subtitle})` : ''}` : ''}
                            onChange={(event) => setQuery(event.target.value)}
                            placeholder={placeholder}
                        />
                        <Combobox.Button className="absolute inset-y-0 right-0 flex items-center pr-3">
                            <ChevronUpDownIcon
                                className="h-5 w-5 text-zinc-400"
                                aria-hidden="true"
                            />
                        </Combobox.Button>
                    </div>
                    <Transition
                        as={Fragment}
                        leave="transition ease-in duration-100"
                        leaveFrom="opacity-100"
                        leaveTo="opacity-0"
                        afterLeave={() => setQuery('')}
                    >
                        <Combobox.Options className="absolute z-50 mt-1 max-h-60 w-full overflow-auto rounded-lg bg-white dark:bg-zinc-900 py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none border border-zinc-200 dark:border-zinc-800">
                            {filteredOptions.length === 0 ? (
                                <div className="relative cursor-default select-none px-4 py-2 text-zinc-500 dark:text-zinc-400 text-sm">
                                    {emptyText}
                                </div>
                            ) : (
                                <>
                                    {value && (
                                        <Combobox.Option
                                            value=""
                                            className={({ active }) =>
                                                `relative cursor-pointer select-none py-2 pl-10 pr-4 ${active ? 'bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-400' : 'text-zinc-700 dark:text-zinc-300'
                                                }`
                                            }
                                        >
                                            {({ selected }) => (
                                                <>
                                                    <span className={`block truncate ${selected ? 'font-semibold' : 'font-normal'}`}>
                                                        {placeholder || 'Nenhum'}
                                                    </span>
                                                    {selected && (
                                                        <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-brand-600 dark:text-brand-400">
                                                            <CheckIcon className="h-5 w-5" aria-hidden="true" />
                                                        </span>
                                                    )}
                                                </>
                                            )}
                                        </Combobox.Option>
                                    )}
                                    {filteredOptions.map((option) => (
                                        <Combobox.Option
                                            key={option.id}
                                            className={({ active }) =>
                                                `relative cursor-pointer select-none py-2 pl-10 pr-4 ${active ? 'bg-brand-50 dark:bg-brand-900/20 text-brand-700 dark:text-brand-400' : 'text-zinc-700 dark:text-zinc-300'
                                                }`
                                            }
                                            value={option.id}
                                        >
                                            {({ selected, active }) => (
                                                <>
                                                    <div className="flex flex-col">
                                                        <span className={`block truncate ${selected ? 'font-semibold' : 'font-normal'}`}>
                                                            {option.name}
                                                        </span>
                                                        {option.subtitle && (
                                                            <span className="text-xs text-zinc-500 dark:text-zinc-400">
                                                                {option.subtitle}
                                                            </span>
                                                        )}
                                                    </div>
                                                    {selected && (
                                                        <span className="absolute inset-y-0 left-0 flex items-center pl-3 text-brand-600 dark:text-brand-400">
                                                            <CheckIcon className="h-5 w-5" aria-hidden="true" />
                                                        </span>
                                                    )}
                                                </>
                                            )}
                                        </Combobox.Option>
                                    ))}
                                </>
                            )}
                        </Combobox.Options>
                    </Transition>
                </div>
            </Combobox>
            {helperText && (
                <p className="mt-1 text-xs text-zinc-500">
                    {helperText}
                </p>
            )}
        </div>
    );
}
