import { useMemo, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Check, ChevronsUpDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Input } from "@/components/ui/input";

export interface SearchableOption {
  value: string;
  label: string;
}

interface SearchableSelectProps {
  value: string;
  placeholder: string;
  options: SearchableOption[];
  onValueChange: (value: string) => void;
  emptyMessage?: string;
}

export default function SearchableSelect({
  value,
  placeholder,
  options,
  onValueChange,
  emptyMessage = "Không có dữ liệu",
}: SearchableSelectProps) {
  const [open, setOpen] = useState(false);
  const [triggerSearch, setTriggerSearch] = useState("");

  const selectedLabel = useMemo(
    () => options.find((option) => option.value === value)?.label,
    [options, value],
  );
  const filteredOptions = useMemo(() => {
    const normalized = triggerSearch.trim().toLowerCase();
    if (!normalized) return options;
    return options.filter((option) => option.label.toLowerCase().includes(normalized));
  }, [options, triggerSearch]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <div className="relative">
          <Input
            role="combobox"
            aria-expanded={open}
            value={triggerSearch || selectedLabel || ""}
            placeholder={placeholder}
            onFocus={() => setOpen(true)}
            onChange={(e) => {
              setTriggerSearch(e.target.value);
              if (value) onValueChange("");
            }}
            className="pr-8"
          />
          <ChevronsUpDown className="pointer-events-none absolute right-2 top-1/2 h-4 w-4 -translate-y-1/2 opacity-50" />
        </div>
      </PopoverTrigger>
      <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0" align="start">
        <Command>
          <CommandInput placeholder="Tìm kiếm..." value={triggerSearch} onValueChange={setTriggerSearch} />
          <CommandList>
            <CommandEmpty>{emptyMessage}</CommandEmpty>
            <CommandGroup>
              {filteredOptions.map((option) => (
                <CommandItem
                  key={option.value}
                  value={option.label}
                  onSelect={() => {
                    onValueChange(option.value === value ? "" : option.value);
                    setTriggerSearch("");
                    setOpen(false);
                  }}
                >
                  <Check className={cn("mr-2 h-4 w-4", value === option.value ? "opacity-100" : "opacity-0")} />
                  {option.label}
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
