import * as React from "react";
import {
    Popover,
    PopoverTrigger,
    PopoverContent,
} from "@/components/ui/popover";
import {
    Command,
    CommandInput,
    CommandList,
    CommandItem,
    CommandEmpty,
} from "@/components/ui/command";
import { Check, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";

export interface Option {
    value: string;
    label: string;
    searchText?: string;
}

interface Props {
    value?: string;
    onChange?: (v: string) => void;
    options: Option[];
    placeholder?: string;
    emptyLabel?: string;
    className?: string;
    disabled?: boolean;
    // For API-based search
    onSearch?: (searchTerm: string) => void;
    isSearching?: boolean;
}

export function SearchableSelect({
    value,
    onChange,
    options,
    placeholder = "Select...",
    emptyLabel = "No results found.",
    className,
    disabled = false,
    onSearch,
    isSearching = false,
}: Props) {
    const [open, setOpen] = React.useState(false);
    const [searchValue, setSearchValue] = React.useState("");
    const selected = options.find((o) => o.value === value);

    React.useEffect(() => { if (disabled && open) setOpen(false); }, [disabled, open]);

    // Handle search input changes
    const handleSearchChange = (value: string) => {
        setSearchValue(value);
        if (onSearch) {
            onSearch(value);
        }
    };

    // Determine if we should use local filtering or API-based search
    const shouldFilter = !onSearch;

    return (
        <Popover open={disabled ? false : open} onOpenChange={(o) => !disabled && setOpen(o)}>
            <PopoverTrigger asChild>
                <button
                    type="button"
                    role="combobox"
                    className={cn(
                        "w-full flex items-center justify-between border rounded-lg px-4 py-2 text-left bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-primary/20",
                        disabled && "opacity-50 cursor-not-allowed",
                        className
                    )}
                    disabled={disabled}
                    aria-disabled={disabled}
                >
                    <span className={selected ? "text-gray-900" : "text-gray-400"}>
                        {selected ? selected.label : placeholder}
                    </span>
                    <ChevronDown className="opacity-50 h-4 w-4 shrink-0" />
                </button>
            </PopoverTrigger>
            <PopoverContent
                className="p-0 w-[--radix-popover-trigger-width]"
                align="start"
                sideOffset={4}
            >
                <Command shouldFilter={shouldFilter}>
                    <CommandInput
                        placeholder="Search..."
                        value={searchValue}
                        onValueChange={handleSearchChange}
                    />
                    <CommandList>
                        <CommandEmpty>
                            {isSearching ? "Searching..." : emptyLabel}
                        </CommandEmpty>
                        {options.map((opt) => (
                            <CommandItem
                                key={opt.value}
                                value={opt.searchText || opt.label || opt.value}
                                onSelect={() => {
                                    onChange?.(opt.value);
                                    setOpen(false);
                                    setSearchValue("");
                                }}
                            >
                                <Check
                                    className={cn(
                                        "mr-2 h-4 w-4 flex-shrink-0",
                                        opt.value === value ? "opacity-100" : "opacity-0"
                                    )}
                                />
                                {opt.label}
                            </CommandItem>
                        ))}
                    </CommandList>
                </Command>
            </PopoverContent>
        </Popover>
    );
}
