"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useDeferredValue, useMemo, useState, useTransition } from "react";
import { createPerson, logout } from "@/app/actions";
import type { ItemKind } from "@/db/schema";
import { KIND_ORDER } from "@/lib/kinds";
import { norm } from "@/lib/text";
import { TONE } from "./Chip";
import { Wordmark } from "./Wordmark";

export type ListPerson = {
  id: string;
  name: string;
  notes: string;
  updatedBy: "casa" | "amico";
  counts: Record<ItemKind, number>;
  // Etichette in ordine di importanza (allergie prima), per anteprima e ricerca
  labels: { kind: ItemKind; label: string }[];
};

export function PeopleList({ people, preselected }: { people: ListPerson[]; preselected: string[] }) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const q = norm(useDeferredValue(query));
  const [dinner, setDinner] = useState(preselected.length > 0);
  const [selected, setSelected] = useState<string[]>(preselected);
  const [adding, setAdding] = useState(false);
  const [newName, setNewName] = useState("");
  const [creating, startCreate] = useTransition();

  const results = useMemo(() => {
    if (!q) return people.map((p) => ({ p, hits: [] as ListPerson["labels"] }));
    return people
      .map((p) => ({ p, byName: norm(p.name).includes(q), hits: p.labels.filter((l) => norm(l.label).includes(q)) }))
      .filter((r) => r.byName || r.hits.length > 0)
      .map(({ p, hits }) => ({ p, hits }));
  }, [people, q]);

  const toggle = (id: string) => setSelected((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]));

  return (
    <div className="flex min-h-dvh flex-col">
      <header className="gingham safe-top sticky top-0 z-20 rounded-b-[28px] shadow-[0_6px_20px_-12px_rgba(28,42,82,0.6)]">
        <div className="mx-auto max-w-2xl">
        <div className="flex items-center justify-between gap-3 px-5 pt-4 pb-3">
          <Wordmark className="text-[40px] [text-shadow:0_2px_0_rgba(28,42,82,0.35)]" />
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => {
                setDinner((d) => !d);
                setSelected([]);
              }}
              aria-pressed={dinner}
              className={`h-10 rounded-field px-4 text-sm font-extrabold shadow-[0_3px_0_rgba(28,42,82,0.3)] ${dinner ? "bg-hi text-hi-ink" : "bg-white/95 text-[#1c2a52]"}`}
            >
              {dinner ? "Chiudi" : "Cena"}
            </button>
            <button
              type="button"
              onClick={() => setAdding((a) => !a)}
              aria-label="Aggiungi una persona"
              aria-expanded={adding}
              className="grid size-10 place-items-center rounded-field bg-hi text-2xl leading-none font-extrabold text-hi-ink shadow-[0_3px_0_rgba(28,42,82,0.3)]"
            >
              {adding ? "×" : "+"}
            </button>
          </div>
        </div>

        {adding && (
          <form
            className="flex gap-2 px-4 pb-3"
            onSubmit={(e) => {
              e.preventDefault();
              if (newName.trim()) startCreate(() => createPerson(newName));
            }}
          >
            <input
              id="new-person"
              autoFocus
              value={newName}
              onChange={(e) => setNewName(e.target.value)}
              placeholder="Nome della nuova persona"
              maxLength={60}
              className="min-w-0 flex-1 rounded-field bg-white px-4 py-3 text-base font-semibold text-[#1c2a52] placeholder:text-[#646d86]"
            />
            <button type="submit" disabled={!newName.trim() || creating} className="rounded-field bg-hi px-5 font-extrabold text-hi-ink disabled:opacity-60">
              {creating ? "…" : "Crea"}
            </button>
          </form>
        )}

        <div className="px-4 pb-5">
          <label className="relative block">
            <span className="sr-only">Cerca</span>
            <svg aria-hidden viewBox="0 0 20 20" className="pointer-events-none absolute top-1/2 left-4 size-5 -translate-y-1/2 text-[#646d86]">
              <circle cx="9" cy="9" r="6" fill="none" stroke="currentColor" strokeWidth="2.2" />
              <path d="m13.5 13.5 4 4" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" />
            </svg>
            <input
              id="search"
              type="search"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder="Cerca un amico o un cibo…"
              autoComplete="off"
              enterKeyHint="search"
              className="w-full rounded-field bg-white py-3.5 pr-4 pl-11 text-base font-semibold text-[#1c2a52] shadow-[0_3px_0_rgba(28,42,82,0.25)] placeholder:font-semibold placeholder:text-[#646d86]"
            />
          </label>
        </div>
        </div>
      </header>
      <div className="mx-auto flex w-full max-w-2xl flex-1 flex-col">

      {dinner && (
        <p className="mx-4 mt-3 rounded-card bg-hi px-4 py-3 text-[15px] font-semibold text-hi-ink">
          Tocca chi viene a cena: poi vedi insieme cosa evitare.
        </p>
      )}

      <div className="flex items-baseline justify-between px-5 pt-4 pb-2 text-xs font-extrabold tracking-wider text-muted uppercase">
        <span>
          {q ? `${results.length} su ${people.length}` : `${people.length} amici`}
        </span>
      </div>

      <ul className={`flex flex-col gap-2 px-3 ${dinner && selected.length ? "pb-28" : "pb-6"}`}>
        {results.map(({ p, hits }) => {
          const isSel = selected.includes(p.id);
          const avoid = p.labels.filter((l) => l.kind !== "favorite");
          const preview = hits.length ? hits : (avoid.length ? avoid : p.labels).slice(0, 5);
          const inner = (
            <>
              {!dinner && <Avatar name={p.name} />}
              <div className="flex min-w-0 flex-1 flex-col gap-0.5">
                <div className="flex items-center gap-2">
                  <span className="truncate text-[17px] font-extrabold">{p.name}</span>
                  {p.updatedBy === "amico" && (
                    <span className="shrink-0 rounded-chip bg-hi px-2 py-0.5 text-[11px] font-extrabold text-hi-ink">aggiornata dal link</span>
                  )}
                </div>
                <p className="truncate text-sm text-muted">
                  {preview.length === 0 && (p.notes || "Nessuna indicazione")}
                  {preview.map((l, i) => (
                    <span key={i}>
                      {i > 0 && " · "}
                      <span className={l.kind === "allergy" ? "font-semibold text-all" : l.kind === "intolerance" ? "font-semibold text-int" : l.kind === "favorite" ? "text-fav" : hits.length ? "text-ink" : ""}>
                        {l.label}
                      </span>
                    </span>
                  ))}
                </p>
              </div>
              <Counts counts={p.counts} />
            </>
          );
          return (
            <li key={p.id}>
              {dinner ? (
                <button
                  type="button"
                  onClick={() => toggle(p.id)}
                  aria-pressed={isSel}
                  className={`flex w-full items-center gap-3 rounded-card border-2 bg-surface px-3.5 py-3 text-left transition-colors ${isSel ? "border-blue" : "border-line"}`}
                >
                  <span className={`grid size-10 shrink-0 place-items-center rounded-full border-2 ${isSel ? "border-blue bg-blue text-white" : "border-line"}`}>
                    {isSel && (
                      <svg viewBox="0 0 16 16" className="size-5" aria-hidden>
                        <path d="m3.5 8.5 3 3 6-7" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    )}
                  </span>
                  {inner}
                </button>
              ) : (
                <Link href={`/persona/${p.id}`} className="flex items-center gap-3 rounded-card border-2 border-line bg-surface px-3.5 py-3 transition-transform active:scale-[0.98]">
                  {inner}
                </Link>
              )}
            </li>
          );
        })}
        {results.length === 0 && (
          <li className="px-4 py-10 text-center text-muted">
            Nessuno corrisponde a “{query}”.
          </li>
        )}
      </ul>

      </div>

      {!dinner && (
        <footer className="safe-bottom mt-auto flex justify-center px-4 py-6">
          <form action={logout}>
            <button type="submit" className="text-sm text-muted underline">
              Esci
            </button>
          </form>
        </footer>
      )}

      {dinner && selected.length > 0 && (
        <div className="safe-bottom fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg/95 backdrop-blur">
          <div className="mx-auto flex max-w-2xl px-4 py-3">
            <button
              type="button"
              onClick={() => router.push(`/cena?ospiti=${selected.join(",")}`)}
              className="flex-1 rounded-field bg-accent py-4 text-base font-extrabold text-accent-ink"
            >
              Riepilogo per {selected.length} {selected.length === 1 ? "persona" : "persone"} →
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function Counts({ counts }: { counts: Record<ItemKind, number> }) {
  const total = KIND_ORDER.reduce((s, k) => s + counts[k], 0);
  if (!total) return null;
  return (
    <span className="flex shrink-0 items-center gap-1" aria-label={KIND_ORDER.map((k) => `${counts[k]} ${k}`).join(", ")}>
      {KIND_ORDER.filter((k) => counts[k] > 0).map((k) => (
        <span
          key={k}
          className={`grid h-[22px] min-w-[22px] place-items-center rounded-full px-1.5 text-xs font-extrabold text-white tabular-nums ${TONE[k].dot}`}
        >
          {counts[k]}
        </span>
      ))}
    </span>
  );
}

function Avatar({ name }: { name: string }) {
  return (
    <span aria-hidden className="grid size-10 shrink-0 place-items-center rounded-full bg-hi text-base font-extrabold text-hi-ink">
      {name.trim()[0]?.toUpperCase()}
    </span>
  );
}
