"use client";

import { X } from "lucide-react";

// Dropdown-to-add, chip-to-remove multi-select for short, fixed option
// lists (no search needed) — e.g. academic titles. The dropdown only offers
// options not yet picked; the reset key forces the <select> back to its
// placeholder after each pick instead of showing the just-added option.
export function Picklist({
  options,
  value,
  onChange,
  placeholder = "Hinzufügen…",
}: {
  options: string[];
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
}) {
  const available = options.filter((o) => !value.includes(o));

  function remove(option: string) {
    onChange(value.filter((v) => v !== option));
  }

  return (
    <div className="flex flex-col gap-2">
      <select
        key={value.length}
        defaultValue=""
        onChange={(e) => {
          if (e.target.value) onChange([...value, e.target.value]);
        }}
        disabled={available.length === 0}
        className="w-full rounded border border-border px-3 py-2 text-sm disabled:bg-surface disabled:text-ink-muted"
      >
        <option value="" disabled>
          {available.length > 0 ? placeholder : "Alle Optionen ausgewählt"}
        </option>
        {available.map((o) => (
          <option key={o} value={o}>
            {o}
          </option>
        ))}
      </select>
      {value.length > 0 && (
        <div className="flex flex-wrap gap-1.5">
          {value.map((v) => (
            <span key={v} className="flex items-center gap-1 rounded-full bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white">
              {v}
              <button type="button" onClick={() => remove(v)} aria-label={`${v} entfernen`} className="text-white/80 hover:text-white">
                <X className="h-3 w-3" />
              </button>
            </span>
          ))}
        </div>
      )}
    </div>
  );
}
