import { useMemo, useState, type WheelEvent } from "react";
import { Check, ChevronsUpDown } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { canonicalOptionLabel, dedupeOptions, normalizeOptionKey } from "@/lib/optionUtils";

function handleDropdownWheel(event: WheelEvent<HTMLDivElement>) {
  event.preventDefault();
  event.stopPropagation();
  event.currentTarget.scrollTop += event.deltaY;
}

interface SearchableSelectProps {
  value: string;
  options: string[];
  onValueChange: (value: string) => void;
  placeholder?: string;
  searchPlaceholder?: string;
  emptyText?: string;
  disabled?: boolean;
  clearLabel?: string;
}

export function SearchableSelect({
  value,
  options,
  onValueChange,
  placeholder = "Seleccionar…",
  searchPlaceholder = "Buscar…",
  emptyText = "No hay resultados.",
  disabled = false,
  clearLabel,
}: SearchableSelectProps) {
  const [open, setOpen] = useState(false);

  const normalizedOptions = useMemo(() => {
    const unique = new Map<string, string>();

    for (const option of dedupeOptions(options)) {
      const label = canonicalOptionLabel(option);
      const key = normalizeOptionKey(label);
      if (!key || unique.has(key)) continue;
      unique.set(key, label);
    }

    return Array.from(unique.values());
  }, [options]);

  const selectedLabel = useMemo(() => {
    const valueKey = normalizeOptionKey(value);
    return normalizedOptions.find((option) => normalizeOptionKey(option) === valueKey) ?? value;
  }, [normalizedOptions, value]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="outline"
          role="combobox"
          aria-expanded={open}
          disabled={disabled}
          className={cn(
            "h-10 w-full justify-between rounded-md border-border bg-background px-3 font-normal hover:bg-background",
            !selectedLabel && "text-muted-foreground",
          )}
        >
          <span className="truncate">{selectedLabel || placeholder}</span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        align="start"
        className="w-[min(92vw,560px)] min-w-[var(--radix-popover-trigger-width)] p-0"
      >
        <Command>
          <CommandInput placeholder={searchPlaceholder} />
          <CommandList className="overscroll-contain" onWheel={handleDropdownWheel}>
            <CommandEmpty>{emptyText}</CommandEmpty>
            <CommandGroup>
              {clearLabel && (
                <>
                  <CommandItem
                    key="__clear__"
                    value={`__clear_${clearLabel}`}
                    onSelect={() => {
                      onValueChange("");
                      setOpen(false);
                    }}
                  >
                    <Check className={cn("mr-2 h-4 w-4", !value ? "opacity-100" : "opacity-0")} />
                    <span className="whitespace-normal break-words font-medium">{clearLabel}</span>
                  </CommandItem>
                  {normalizedOptions.length > 0 && <CommandSeparator className="my-1" />}
                </>
              )}

              {normalizedOptions.map((option) => (
                <CommandItem
                  key={normalizeOptionKey(option)}
                  value={`${normalizeOptionKey(option)} ${option}`}
                  onSelect={() => {
                    onValueChange(option);
                    setOpen(false);
                  }}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4",
                      normalizeOptionKey(value) === normalizeOptionKey(option)
                        ? "opacity-100"
                        : "opacity-0",
                    )}
                  />
                  <span className="whitespace-normal break-words leading-snug">{option}</span>
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
