"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { ArrowLeft, Copy, ExternalLink, Plus, Search, Trash2 } from "lucide-react";

type BoletimLinha = {
  id: string;
  slug: string;
  title: string;
  subtitle: string | null;
  tag: string | null;
  status: string;
  published_at: string | null;
  updated_at: string | null;
  palavras: number;
};

function quandoLegivel(valor: string | null) {
  if (!valor) return "—";
  const data = new Date(valor);
  return Number.isNaN(data.getTime()) ? "—" : data.toLocaleDateString("pt-BR");
}

export default function BoletinsListClient({
  initialRows,
  base,
}: {
  initialRows: BoletimLinha[];
  base: string;
}) {
  const [linhas, setLinhas] = useState<BoletimLinha[]>(() => initialRows || []);
  const [busca, setBusca] = useState("");
  const [erro, setErro] = useState("");
  const [apagando, setApagando] = useState("");
  const [confirmando, setConfirmando] = useState<BoletimLinha | null>(null);
  const [copiado, setCopiado] = useState("");

  const filtradas = useMemo(() => {
    const alvo = busca.trim().toLowerCase();
    if (!alvo) return linhas;
    return linhas.filter((linha) => `${linha.title} ${linha.subtitle ?? ""} ${linha.slug}`.toLowerCase().includes(alvo));
  }, [linhas, busca]);

  async function copiarEndereco(linha: BoletimLinha) {
    const endereco = `${base}/${linha.slug}`;
    try {
      await navigator.clipboard.writeText(endereco);
      setCopiado(linha.id);
      setTimeout(() => setCopiado(""), 1800);
    } catch {
      setErro("Não consegui copiar. O endereço é " + endereco);
    }
  }

  async function excluir(linha: BoletimLinha) {
    setApagando(linha.id);
    setErro("");
    try {
      const resposta = await fetch(`/api/bulletins?id=${encodeURIComponent(linha.id)}`, { method: "DELETE" });
      const corpo = (await resposta.json().catch(() => null)) as { error?: string } | null;
      if (!resposta.ok) throw new Error(corpo?.error || "Não foi possível excluir.");
      setLinhas((antes) => antes.filter((item) => item.id !== linha.id));
      setConfirmando(null);
    } catch (falha) {
      setErro(falha instanceof Error ? falha.message : "Não foi possível excluir.");
    } finally {
      setApagando("");
    }
  }

  return (
    <div className="min-h-screen bg-slate-50/50 p-6 sm:p-10 font-sans">
      <div className="mx-auto max-w-[1080px]">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div>
            <Link href="/" className="inline-flex items-center gap-2 text-sm font-medium text-slate-500 hover:text-slate-900">
              <ArrowLeft size={16} />
              Voltar ao painel
            </Link>
            <h1 className="mt-3 text-2xl font-semibold tracking-tight text-slate-900">Boletins</h1>
            <p className="mt-1 text-sm text-slate-500">
              As páginas de aviso publicadas em <span className="font-semibold text-slate-700">{base}</span>. O endereço
              de cada uma é o link que você cola no botão do popup.
            </p>
          </div>
          <Link
            href="/boletins/novo"
            className="inline-flex h-11 items-center gap-2 rounded-xl bg-slate-900 px-5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 active:scale-95"
          >
            <Plus size={16} />
            Novo boletim
          </Link>
        </div>

        <div className="mt-6 flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 shadow-sm">
          <Search size={16} className="text-slate-400" />
          <input
            value={busca}
            onChange={(evento) => setBusca(evento.target.value)}
            placeholder="Buscar por título ou endereço"
            className="h-11 flex-1 border-0 bg-transparent text-sm text-slate-900 outline-none placeholder:text-slate-400"
          />
        </div>

        {erro ? (
          <div className="mt-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700">{erro}</div>
        ) : null}

        {/* Listagem corrida, com divisória quase invisível: nada de cartão
            flutuante por linha. */}
        <div className="mt-4 overflow-hidden rounded-2xl border border-slate-200 bg-white">
          {filtradas.map((linha) => {
            const publicado = linha.status === "published";
            return (
              <div
                key={linha.id}
                className="flex flex-wrap items-center gap-4 border-b border-slate-100/70 px-5 py-4 transition last:border-b-0 hover:bg-slate-50/60"
              >
                <div className="min-w-[240px] flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <Link href={`/boletins/${linha.id}`} className="text-sm font-semibold text-slate-900 hover:text-indigo-700">
                      {linha.title}
                    </Link>
                    {linha.tag ? (
                      <span className="rounded-full bg-indigo-50 px-2 py-0.5 text-[11px] font-semibold text-indigo-700">
                        {linha.tag}
                      </span>
                    ) : null}
                    <span
                      className={[
                        "rounded-md border px-2 py-0.5 text-[11px] font-bold",
                        publicado
                          ? "border-emerald-200 bg-emerald-50 text-emerald-700"
                          : "border-amber-200 bg-amber-50 text-amber-800",
                      ].join(" ")}
                    >
                      {publicado ? "Publicado" : "Rascunho"}
                    </span>
                  </div>
                  <p className="mt-0.5 line-clamp-1 text-xs text-slate-500">{linha.subtitle || "Sem linha de apoio"}</p>
                  <p className="mt-1 text-[11px] text-slate-400">
                    /{linha.slug} · {Math.max(1, Math.round(linha.palavras / 200))} min de leitura ·{" "}
                    {publicado ? `publicado em ${quandoLegivel(linha.published_at)}` : `editado em ${quandoLegivel(linha.updated_at)}`}
                  </p>
                </div>

                <div className="flex items-center gap-1">
                  <button
                    type="button"
                    onClick={() => void copiarEndereco(linha)}
                    title="Copiar o endereço"
                    aria-label={`Copiar endereço de ${linha.title}`}
                    className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-500 transition hover:bg-slate-100 hover:text-slate-900"
                  >
                    <Copy size={15} />
                  </button>
                  {publicado ? (
                    <a
                      href={`${base}/${linha.slug}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      title="Abrir a página"
                      className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-500 transition hover:bg-slate-100 hover:text-slate-900"
                    >
                      <ExternalLink size={15} />
                    </a>
                  ) : null}
                  <Link
                    href={`/boletins/${linha.id}`}
                    className="ml-1 inline-flex h-9 items-center rounded-lg border border-slate-200 bg-white px-3.5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
                  >
                    Editar
                  </Link>
                  <button
                    type="button"
                    onClick={() => setConfirmando(linha)}
                    title="Excluir"
                    aria-label={`Excluir ${linha.title}`}
                    className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-400 transition hover:bg-rose-50 hover:text-rose-600"
                  >
                    <Trash2 size={15} />
                  </button>
                </div>

                {copiado === linha.id ? (
                  <span className="w-full text-right text-[11px] font-semibold text-emerald-600">Endereço copiado</span>
                ) : null}
              </div>
            );
          })}

          {filtradas.length === 0 ? (
            <div className="px-6 py-14 text-center">
              <p className="text-sm font-medium text-slate-700">
                {linhas.length === 0 ? "Nenhum boletim ainda." : "Nada encontrado para essa busca."}
              </p>
              <p className="mt-1 text-xs text-slate-500">
                {linhas.length === 0
                  ? "Escreva o primeiro e o endereço dele vira o link do popup."
                  : "Tente outro termo."}
              </p>
            </div>
          ) : null}
        </div>
      </div>

      {confirmando ? (
        <div className="fixed inset-0 z-50 grid place-items-center bg-slate-900/50 p-4" onClick={() => setConfirmando(null)}>
          <div className="w-full max-w-md rounded-2xl bg-white p-6 shadow-xl" onClick={(e) => e.stopPropagation()}>
            <h2 className="text-lg font-semibold text-slate-900">Excluir este boletim?</h2>
            <p className="mt-2 text-sm text-slate-500">
              &ldquo;{confirmando.title}&rdquo; sai do ar na hora. Quem tiver o link vai encontrar página não achada, e
              popup que aponte para ele fica com botão quebrado.
            </p>
            <div className="mt-6 flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setConfirmando(null)}
                className="inline-flex h-11 items-center rounded-xl border border-slate-200 bg-white px-5 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
              >
                Voltar
              </button>
              <button
                type="button"
                onClick={() => void excluir(confirmando)}
                disabled={apagando === confirmando.id}
                className="inline-flex h-11 items-center rounded-xl bg-rose-600 px-5 text-sm font-semibold text-white transition hover:bg-rose-500 disabled:opacity-50"
              >
                {apagando === confirmando.id ? "Excluindo…" : "Excluir"}
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
