"use client";

import * as React from "react";
import * as Popover from "@radix-ui/react-popover";
import { Check, ChevronsUpDown } from "lucide-react";
import { Command } from "cmdk";
import { cn } from "../../lib/utils";
import { Button } from "./button";

export type ComboOption = { value: string; label: string };

export function Combobox({ value, onChange, options, placeholder }: { value: string; onChange: (value: string) => void; options: ComboOption[]; placeholder: string }) {
  const [open, setOpen] = React.useState(false);
  const selected = options.find((o) => o.value === value);

  return (
    <Popover.Root open={open} onOpenChange={setOpen}>
      <Popover.Trigger asChild>
        <Button variant="outline" type="button" className="w-full justify-between rounded-lg border-slate-300 text-slate-700">
          {selected ? selected.label : placeholder}
          <ChevronsUpDown className="ml-2 h-4 w-4 opacity-50" />
        </Button>
      </Popover.Trigger>
      <Popover.Portal>
        <Popover.Content className="z-50 w-[var(--radix-popover-trigger-width)] rounded-lg border border-slate-200 bg-white p-0 shadow-[0_8px_24px_rgba(15,23,42,0.08)]" sideOffset={6}>
          <Command className="max-h-64 overflow-auto">
            <Command.Input className="h-10 w-full border-b border-slate-200 px-3 text-sm outline-none" placeholder="Search..." />
            <Command.List>
              <Command.Empty className="p-3 text-sm text-slate-500">No option found.</Command.Empty>
              <Command.Group>
                {options.map((option) => (
                  <Command.Item
                    key={option.value}
                    value={`${option.label} ${option.value}`}
                    onSelect={() => {
                      onChange(option.value);
                      setOpen(false);
                    }}
                    className="flex cursor-default items-center gap-2 px-3 py-2 text-sm hover:bg-slate-100"
                  >
                    <Check className={cn("h-4 w-4", value === option.value ? "opacity-100" : "opacity-0")} />
                    {option.label}
                  </Command.Item>
                ))}
              </Command.Group>
            </Command.List>
          </Command>
        </Popover.Content>
      </Popover.Portal>
    </Popover.Root>
  );
}
