// BEGIN CHANGE: Admin Notificacoes - templates on_register + broadcast
"use client";

import { useCallback, useEffect, useState } from "react";
import { apiUrl } from "@/lib/api";

type Template = {
  id: number;
  title: string;
  body: string;
  link: string;
  onRegister: boolean;
  created: number;
};

const emptyForm = { id: 0, title: "", body: "", link: "", onRegister: true };

export function AdminNotify({ token }: { token: string }) {
  const [templates, setTemplates] = useState<Template[]>([]);
  const [form, setForm] = useState(emptyForm);
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState("");
  const [err, setErr] = useState("");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");

  const [bcTitle, setBcTitle] = useState("");
  const [bcBody, setBcBody] = useState("");
  const [bcLink, setBcLink] = useState("");

  const load = useCallback(async () => {
    setStatus("loading");
    setErr("");
    try {
      const r = await fetch(apiUrl("notifications.php?admin=1"), {
        headers: { Authorization: `Bearer ${token}` },
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao carregar.");
        setStatus("error");
        return;
      }
      setTemplates(json.templates ?? []);
      setStatus("ok");
    } catch {
      setErr("Falha de rede.");
      setStatus("error");
    }
  }, [token]);

  useEffect(() => {
    void load();
  }, [load]);

  async function saveTemplate() {
    setBusy(true);
    setMsg("");
    setErr("");
    try {
      const r = await fetch(apiUrl("notifications.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          action: "template_save",
          id: form.id,
          title: form.title,
          body: form.body,
          link: form.link,
          onRegister: form.onRegister,
        }),
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao salvar.");
        return;
      }
      setTemplates(json.templates ?? []);
      setForm(emptyForm);
      setMsg(form.id > 0 ? "Template atualizado." : "Template criado.");
    } catch {
      setErr("Falha ao salvar.");
    } finally {
      setBusy(false);
    }
  }

  async function deleteTemplate(id: number) {
    if (!confirm("Excluir este template?")) return;
    setBusy(true);
    setMsg("");
    setErr("");
    try {
      const r = await fetch(apiUrl("notifications.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ action: "template_delete", id }),
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao excluir.");
        return;
      }
      setTemplates(json.templates ?? []);
      if (form.id === id) setForm(emptyForm);
      setMsg("Template excluido.");
    } catch {
      setErr("Falha ao excluir.");
    } finally {
      setBusy(false);
    }
  }

  async function sendBroadcast() {
    setBusy(true);
    setMsg("");
    setErr("");
    try {
      const r = await fetch(apiUrl("notifications.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          action: "broadcast",
          title: bcTitle,
          body: bcBody,
          link: bcLink,
        }),
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || "Falha ao enviar.");
        return;
      }
      setMsg("Broadcast enviado a todos os players.");
      setBcTitle("");
      setBcBody("");
      setBcLink("");
    } catch {
      setErr("Falha ao enviar.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-xl font-semibold">Notificacoes</h2>
        <p className="mt-1 text-sm text-muted">
          Gerencie avisos do sino: templates para contas novas e broadcast global.
        </p>
      </div>

      {msg && <p className="text-sm text-brand">{msg}</p>}
      {err && <p className="text-sm text-red-400">{err}</p>}

      <section className="space-y-3">
        <div>
          <h3 className="text-lg font-medium">Contas novas</h3>
          <p className="mt-1 text-sm text-muted">
            Templates com &quot;Enviar no cadastro&quot; marcado sao copiados para a conta
            ao registrar. Placeholders:{" "}
            <code className="text-xs">{"{dayLabel}"}</code>,{" "}
            <code className="text-xs">{"{days}"}</code> (de{" "}
            <code className="text-xs">starterPremiumDays</code>).
          </p>
        </div>

        {status === "loading" && (
          <p className="text-sm text-muted">Carregando...</p>
        )}

        <div className="overflow-x-auto rounded-xl border border-border">
          <table className="min-w-full text-left text-sm">
            <thead className="border-b border-border bg-panel text-muted">
              <tr>
                <th className="px-3 py-2">Titulo</th>
                <th className="px-3 py-2">No cadastro</th>
                <th className="px-3 py-2">Acoes</th>
              </tr>
            </thead>
            <tbody>
              {templates.length === 0 && status === "ok" && (
                <tr>
                  <td colSpan={3} className="px-3 py-4 text-muted">
                    Nenhum template.
                  </td>
                </tr>
              )}
              {templates.map((t) => (
                <tr key={t.id} className="border-b border-border/60">
                  <td className="px-3 py-2">
                    <div className="font-medium">{t.title}</div>
                    <div className="mt-0.5 line-clamp-2 text-xs text-muted">
                      {t.body || "-"}
                    </div>
                  </td>
                  <td className="px-3 py-2">
                    {t.onRegister ? "Sim" : "Nao"}
                  </td>
                  <td className="px-3 py-2">
                    <div className="flex flex-wrap gap-2">
                      <button
                        type="button"
                        disabled={busy}
                        className="rounded border border-border px-2 py-1 text-xs disabled:opacity-50"
                        onClick={() =>
                          setForm({
                            id: t.id,
                            title: t.title,
                            body: t.body,
                            link: t.link,
                            onRegister: t.onRegister,
                          })
                        }
                      >
                        Editar
                      </button>
                      <button
                        type="button"
                        disabled={busy}
                        className="rounded border border-red-500/40 px-2 py-1 text-xs text-red-400 disabled:opacity-50"
                        onClick={() => void deleteTemplate(t.id)}
                      >
                        Excluir
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="grid gap-3 rounded-xl border border-border bg-panel p-4">
          <div className="text-sm font-medium">
            {form.id > 0 ? `Editar template #${form.id}` : "Novo template"}
          </div>
          <label className="text-sm">
            <span className="text-muted">Titulo</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={form.title}
              onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
              placeholder="Ex: Bonus de boas-vindas"
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">Mensagem</span>
            <textarea
              className="mt-1 min-h-[100px] w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={form.body}
              onChange={(e) => setForm((f) => ({ ...f, body: e.target.value }))}
              placeholder="Use {dayLabel} para os dias de Premium do config."
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">Link (opcional)</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={form.link}
              onChange={(e) => setForm((f) => ({ ...f, link: e.target.value }))}
              placeholder="/download"
            />
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input
              type="checkbox"
              checked={form.onRegister}
              onChange={(e) =>
                setForm((f) => ({ ...f, onRegister: e.target.checked }))
              }
            />
            <span>Enviar no cadastro (contas novas)</span>
          </label>
          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              disabled={busy || form.title.trim() === ""}
              onClick={() => void saveTemplate()}
              className="rounded bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
            >
              {busy ? "Salvando..." : form.id > 0 ? "Salvar" : "Adicionar"}
            </button>
            {form.id > 0 && (
              <button
                type="button"
                disabled={busy}
                onClick={() => setForm(emptyForm)}
                className="rounded border border-border px-4 py-2 text-sm disabled:opacity-50"
              >
                Cancelar
              </button>
            )}
          </div>
        </div>
      </section>

      <section className="space-y-3">
        <div>
          <h3 className="text-lg font-medium">Broadcast global</h3>
          <p className="mt-1 text-sm text-muted">
            Envia um aviso imediato para todos os players (aparece no sino).
          </p>
        </div>
        <div className="grid gap-3 rounded-xl border border-border bg-panel p-4">
          <label className="text-sm">
            <span className="text-muted">Titulo</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={bcTitle}
              onChange={(e) => setBcTitle(e.target.value)}
              placeholder="Ex: Manutencao programada"
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">Mensagem</span>
            <textarea
              className="mt-1 min-h-[100px] w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={bcBody}
              onChange={(e) => setBcBody(e.target.value)}
              placeholder="Detalhe o aviso (sem HTML)."
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">Link (opcional)</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={bcLink}
              onChange={(e) => setBcLink(e.target.value)}
              placeholder="/news"
            />
          </label>
          <button
            type="button"
            disabled={busy || bcTitle.trim() === ""}
            onClick={() => void sendBroadcast()}
            className="w-fit rounded bg-brand px-4 py-2 text-sm font-medium text-background disabled:opacity-50"
          >
            {busy ? "Enviando..." : "Enviar para todos"}
          </button>
        </div>
      </section>
    </div>
  );
}
// END CHANGE
