"use client";

import { useState } from "react";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useT } from "@/shared/i18n/client";
import { Popover, PopoverContent, PopoverTrigger } from "@/presentation/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/presentation/components/ui/command";

interface Option<V extends string | number> {
  value: V;
  label: string;
}

interface MultiSelectProps<V extends string | number> {
  id?: string;
  options: Option<V>[];
  value: V[];
  onChange: (value: V[]) => void;
  placeholder?: string;
  disabled?: boolean;
}

/** Searchable multi-select with removable chips (audience pickers). */
export function MultiSelect<V extends string | number>({ id, options, value, onChange, placeholder, disabled }: MultiSelectProps<V>) {
  const t = useT();
  const [open, setOpen] = useState(false);
  const selected = options.filter((o) => value.includes(o.value));
  const toggle = (v: V) => onChange(value.includes(v) ? value.filter((x) => x !== v) : [...value, v]);

  return (
    <div className="space-y-1.5">
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <button
            id={id}
            type="button"
            disabled={disabled}
            aria-expanded={open}
            className="flex h-9 w-full items-center justify-between rounded-md border border-input bg-background px-3 text-sm shadow-xs disabled:cursor-not-allowed disabled:opacity-50 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50"
          >
            <span className={cn("truncate", !selected.length && "text-muted-foreground")}>
              {selected.length ? t.announcements.audience.selected(selected.length) : placeholder ?? t.announcements.audience.any}
            </span>
            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
          </button>
        </PopoverTrigger>
        <PopoverContent className="w-[var(--radix-popover-trigger-width)] min-w-64 p-0" align="start">
          <Command>
            <CommandInput placeholder={t.announcements.audience.searchPlaceholder} />
            <CommandList>
              <CommandEmpty>{t.announcements.audience.none}</CommandEmpty>
              <CommandGroup>
                {options.map((o) => (
                  <CommandItem key={String(o.value)} value={o.label} onSelect={() => toggle(o.value)}>
                    <Check className={cn("mr-2 h-4 w-4", value.includes(o.value) ? "opacity-100" : "opacity-0")} />
                    {o.label}
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
      {selected.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {selected.map((o) => (
            <span key={String(o.value)} className="inline-flex items-center gap-1 rounded-full border bg-muted/50 px-2 py-0.5 text-xs">
              {o.label}
              {!disabled && (
                <button type="button" onClick={() => toggle(o.value)} className="rounded-full hover:text-destructive" aria-label={`${o.label} ×`}>
                  <X className="h-3 w-3" />
                </button>
              )}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
