"use client";

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

type SystemNotice = {
  id: string;
  scope: string;
  title: string | null;
  message: string;
  variant: string;
  dismiss_mode: string;
  active: boolean;
  position: number;
  start_at: string | null;
  end_at: string | null;
  show_on_paths: string[] | null;
  hide_on_paths: string[] | null;
  theme: Record<string, unknown>;
  created_at?: string | null;
  updated_at?: string | null;
};

function formatDate(value: string | null | undefined) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return "";
  return d.toISOString().slice(0, 10);
}

function formatScopeLabel(value: string) {
  if (value === "all") return "Todos os apps";
  if (value === "admin") return "Admin";
  if (value === "owner") return "Owner";
  if (value === "public") return "Catálogo público";
  return value || "—";
}

function formatVariantLabel(value: string) {
  if (value === "info") return "Info";
  if (value === "success") return "Sucesso";
  if (value === "warning") return "Atenção";
  if (value === "danger") return "Urgente";
  return value || "—";
}

function Badge({ active }: { active: boolean }) {
  return (
    <span
      className={[
        "inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold",
        active ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-slate-200 bg-slate-50 text-slate-600",
      ].join(" ")}
    >
      {active ? "Ativa" : "Inativa"}
    </span>
  );
}

function VariantPill({ variant }: { variant: string }) {
  const base = "inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold";
  if (variant === "success") return <span className={`${base} border-emerald-200 bg-emerald-50 text-emerald-700`}>Sucesso</span>;
  if (variant === "warning") return <span className={`${base} border-amber-200 bg-amber-50 text-amber-800`}>Atenção</span>;
  if (variant === "danger") return <span className={`${base} border-rose-200 bg-rose-50 text-rose-700`}>Urgente</span>;
  return <span className={`${base} border-blue-200 bg-blue-50 text-blue-700`}>Info</span>;
}

export default function SystemNoticesListClient({ initialRows }: { initialRows: SystemNotice[] }) {
  const [rows, setRows] = useState<SystemNotice[]>(() => initialRows || []);
  const [query, setQuery] = useState("");
  const [scope, setScope] = useState("todos");
  const [loading, setLoading] = useState(false);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [busyDelete, setBusyDelete] = useState(false);
  const [toast, setToast] = useState<string>("");
  const toastRef = useRef<number | null>(null);

  const scopes = useMemo(
    () => [
      { value: "todos", label: "Escopo: Todos" },
      { value: "all", label: "Todos os apps" },
      { value: "admin", label: "Admin" },
      { value: "owner", label: "Owner" },
      { value: "public", label: "Catálogo público" },
    ],
    []
  );

  const filtered = useMemo(() => {
    const term = query.trim().toLowerCase();
    return rows.filter((row) => {
      if (scope !== "todos" && row.scope !== scope) return false;
      if (!term) return true;
      const hay = `${row.title || ""} ${row.message || ""} ${row.scope || ""} ${row.variant || ""}`.toLowerCase();
      return hay.includes(term);
    });
  }, [rows, query, scope]);

  async function reload(nextScope = scope) {
    setLoading(true);
    try {
      const res = await fetch("/api/system-notices", {
        method: "GET",
        headers: { "content-type": "application/json" },
      });
      const json = (await res.json().catch(() => null)) as { notices?: SystemNotice[] } | null;
      const items = Array.isArray(json?.notices) ? json!.notices! : [];
      setRows(items.map((r) => ({ ...r, theme: r.theme || {} })));
      setDeleteId(null);
      setScope(nextScope);
    } finally {
      setLoading(false);
    }
  }

  function showToast(text: string) {
    setToast(text);
    if (toastRef.current) window.clearTimeout(toastRef.current);
    toastRef.current = window.setTimeout(() => setToast(""), 1600);
  }

  return (
    <div className="min-h-screen bg-slate-50/50 p-6 sm:p-8 font-sans">
      <div className="mx-auto flex max-w-[1600px] flex-col gap-6">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1">
            <div className="flex items-center gap-3">
              <Link
                href="/"
                className="inline-flex h-10 w-10 items-center justify-center rounded-xl bg-white shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 active:scale-95"
                aria-label="Voltar"
                title="Voltar"
              >
                <ArrowLeft className="h-4.5 w-4.5 text-slate-700" />
              </Link>
              <div>
                <h1 className="text-2xl font-bold tracking-tight text-slate-900">Tarjas informativas</h1>
                <p className="text-slate-500">Crie avisos globais com regras de exibição e personalização visual.</p>
              </div>
            </div>
          </div>

          <div className="flex items-center gap-3">
            <Link
              href="/tarjas-informativas/novo"
              className="inline-flex items-center justify-center gap-2 rounded-xl bg-slate-900 px-4 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 active:scale-95"
            >
              <Plus className="h-4.5 w-4.5" />
              Nova tarja
            </Link>
          </div>
        </div>

        <div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
            <div className="flex flex-1 flex-col gap-2 sm:flex-row">
              <div className="flex h-11 flex-1 items-center gap-2 rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-700">
                <Search className="h-4 w-4 text-slate-400" />
                <input
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="Buscar por título, mensagem ou escopo..."
                  className="min-w-0 flex-1 bg-transparent outline-none placeholder:text-slate-400"
                />
              </div>

              <div className="relative">
                <select
                  value={scope}
                  onChange={(e) => {
                    const value = e.target.value;
                    setScope(value);
                  }}
                  className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm font-semibold text-slate-700 shadow-sm ring-0 focus:outline-none sm:w-[260px]"
                >
                  {scopes.map((s) => (
                    <option key={s.value} value={s.value}>
                      {s.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            <div className="flex items-center justify-between gap-3 lg:justify-end">
              <div className="text-xs font-medium text-slate-500">{loading ? "Carregando..." : `${filtered.length} tarja(s)`}</div>
              <button
                type="button"
                onClick={() => reload()}
                className="inline-flex h-11 items-center justify-center rounded-xl bg-white px-4 text-sm font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 active:scale-95"
              >
                Atualizar
              </button>
            </div>
          </div>
        </div>

        <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
          <div className="max-h-[680px] overflow-auto">
            <table className="w-full border-collapse text-sm">
              <thead className="sticky top-0 z-10 bg-white">
                <tr className="border-b border-slate-200 text-xs font-semibold text-slate-500">
                  <th className="px-4 py-3 text-left">Tarja</th>
                  <th className="px-4 py-3 text-left">Escopo</th>
                  <th className="px-4 py-3 text-left">Estilo</th>
                  <th className="px-4 py-3 text-left">Regras</th>
                  <th className="px-4 py-3 text-left">Status</th>
                  <th className="w-[220px] px-4 py-3 text-right">Ações</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((row) => {
                  const schedule =
                    row.start_at || row.end_at
                      ? `${row.start_at ? formatDate(row.start_at) : "—"} → ${row.end_at ? formatDate(row.end_at) : "—"}`
                      : "Sem agendamento";
                  const showRule = row.show_on_paths?.length ? `Mostrar: ${row.show_on_paths.join(", ")}` : "Mostrar: qualquer página";
                  const hideRule = row.hide_on_paths?.length ? `Ocultar: ${row.hide_on_paths.join(", ")}` : "";
                  const isConfirming = deleteId === row.id;
                  return (
                    <tr key={row.id} className="border-b border-slate-100 transition hover:bg-slate-50">
                      <td className="px-4 py-4">
                        <div className="min-w-0">
                          <div className="truncate text-sm font-semibold text-slate-950">{row.title || "Tarja sem título"}</div>
                          <div className="mt-0.5 line-clamp-1 text-xs text-slate-500">{row.message}</div>
                          <div className="mt-1 text-xs text-slate-400">Ordem: {row.position}</div>
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        <div className="text-sm font-semibold text-slate-900">{formatScopeLabel(row.scope)}</div>
                        <div className="mt-0.5 text-xs text-slate-500">{row.scope}</div>
                      </td>
                      <td className="px-4 py-4">
                        <VariantPill variant={row.variant} />
                        <div className="mt-1 text-xs text-slate-500">{formatVariantLabel(row.variant)} • {row.dismiss_mode === "sticky" ? "Sem fechar" : row.dismiss_mode === "session" ? "Sessão" : "Fechável"}</div>
                      </td>
                      <td className="px-4 py-4">
                        <div className="text-xs font-semibold text-slate-700">{schedule}</div>
                        <div className="mt-0.5 text-xs text-slate-500">
                          {showRule}
                          {hideRule ? ` • ${hideRule}` : ""}
                        </div>
                      </td>
                      <td className="px-4 py-4">
                        <Badge active={row.active} />
                      </td>
                      <td className="px-4 py-4 text-right">
                        {isConfirming ? (
                          <div className="inline-flex items-center gap-2">
                            <button
                              type="button"
                              disabled={busyDelete}
                              onClick={() => setDeleteId(null)}
                              className="inline-flex h-9 items-center justify-center rounded-xl bg-white px-3 text-xs font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50 disabled:opacity-60"
                            >
                              Cancelar
                            </button>
                            <button
                              type="button"
                              disabled={busyDelete}
                              onClick={async () => {
                                setBusyDelete(true);
                                try {
                                  const res = await fetch(`/api/system-notices?id=${encodeURIComponent(row.id)}`, { method: "DELETE" });
                                  if (res.ok) {
                                    showToast("Tarja deletada");
                                    await reload();
                                  } else {
                                    showToast("Não foi possível deletar");
                                  }
                                } finally {
                                  setBusyDelete(false);
                                }
                              }}
                              className="inline-flex h-9 items-center justify-center gap-2 rounded-xl bg-rose-600 px-3 text-xs font-semibold text-white shadow-sm transition hover:bg-rose-500 disabled:opacity-60"
                            >
                              <Trash2 className="h-4 w-4" />
                              Confirmar
                            </button>
                          </div>
                        ) : (
                          <div className="inline-flex items-center gap-2">
                            <Link
                              href={`/tarjas-informativas/${encodeURIComponent(row.id)}`}
                              className="inline-flex h-9 items-center justify-center rounded-xl bg-white px-3 text-xs font-semibold text-slate-700 shadow-sm ring-1 ring-slate-200 transition hover:bg-slate-50"
                            >
                              Editar
                            </Link>
                            <button
                              type="button"
                              onClick={() => setDeleteId(row.id)}
                              className="inline-flex h-9 items-center justify-center gap-2 rounded-xl bg-white px-3 text-xs font-semibold text-rose-700 shadow-sm ring-1 ring-rose-200 transition hover:bg-rose-50"
                            >
                              <Trash2 className="h-4 w-4" />
                              Deletar
                            </button>
                          </div>
                        )}
                      </td>
                    </tr>
                  );
                })}
                {filtered.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-4 py-10 text-center text-sm text-slate-500">
                      Nenhuma tarja encontrada.
                    </td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {toast ? (
        <div className="fixed bottom-6 left-1/2 z-[100] -translate-x-1/2 rounded-full bg-slate-900 px-4 py-2 text-sm font-semibold text-white shadow-lg">
          {toast}
        </div>
      ) : null}
    </div>
  );
}
