"use client";

import { useState, useTransition } from "react";
import { X } from "lucide-react";

export function PoolManager({
  label,
  pool,
  onAdd,
  onRemove,
}: {
  label: string;
  pool: string[];
  onAdd: (value: string) => Promise<void>;
  onRemove: (value: string) => Promise<void>;
}) {
  const [input, setInput] = useState("");
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function handleAdd() {
    const trimmed = input.trim();
    if (!trimmed) return;
    if (pool.includes(trimmed)) {
      setError("Valore già presente");
      return;
    }
    setError(null);
    startTransition(async () => {
      await onAdd(trimmed);
      setInput("");
    });
  }

  function handleRemove(value: string) {
    const ok = window.confirm(
      `Eliminare "${value}" da «${label}»?\n\nVerrà rimosso ovunque: sparirà dal menu e da tutte le offerte/servizi che lo usano.`
    );
    if (!ok) return;
    startTransition(() => onRemove(value));
  }

  function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      e.preventDefault();
      handleAdd();
    }
  }

  return (
    <div
      className={`flex flex-col justify-between rounded-xl border border-border-light bg-muted/40 p-5 transition-opacity ${
        isPending ? "opacity-60" : ""
      }`}
    >
      <div>
        <div className="mb-3 flex items-center justify-between">
          <span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
            {label}
          </span>
          <span className="rounded border border-border-light bg-card px-1.5 py-0.5 font-mono text-[10px] font-bold tabular-nums text-tertiary">
            {pool.length}
          </span>
        </div>

        <div className="mb-4 flex flex-wrap gap-1.5">
          {pool.length === 0 ? (
            <div className="w-full py-6 text-center text-xs italic text-tertiary">
              Nessun valore inserito
            </div>
          ) : (
            pool.map((v) => (
              <span
                key={v}
                className="inline-flex items-center gap-1 rounded-md border border-border/60 bg-card py-1 pl-2.5 pr-1.5 text-[11px] font-semibold text-foreground shadow-sm"
              >
                {v}
                <button
                  type="button"
                  onClick={() => handleRemove(v)}
                  disabled={isPending}
                  className="rounded p-0.5 text-tertiary transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-50"
                  aria-label={`Elimina ${v}`}
                  title={`Elimina "${v}" ovunque`}
                >
                  <X className="h-3 w-3" />
                </button>
              </span>
            ))
          )}
        </div>
      </div>

      <input
        type="text"
        value={input}
        onChange={(e) => {
          setInput(e.target.value);
          setError(null);
        }}
        onKeyDown={onKeyDown}
        placeholder="Aggiungi valore..."
        disabled={isPending}
        aria-label={`Aggiungi valore a ${label}`}
        className="w-full rounded-lg border border-border bg-card px-3 py-2 text-xs text-foreground transition-colors placeholder:text-tertiary focus:border-primary focus:outline-none disabled:opacity-50"
      />
      {error && <p className="mt-1.5 text-xs text-destructive">{error}</p>}
    </div>
  );
}
