// BEGIN CHANGE: secoes CMS do painel admin (hero, news, changelog, polls)
"use client";

import { FormEvent, useEffect, useState } from "react";
import { apiUrl } from "@/lib/api";

type Hero = {
  badge: string;
  titlePre: string;
  titleBrand: string;
  subtitle: string;
  updated?: number;
};

type NewsRow = {
  date: number;
  text: string;
  imageId: number;
  hidden: boolean;
  authorId: number;
  author: string;
};

type ChangelogRow = {
  id: number;
  type: string;
  place: string;
  date: number;
  description: string;
};

type PollRow = {
  id: number;
  question: string;
  end: number;
  active: boolean;
  votesAll: number;
  answersCount: number;
};

type Labels = {
  homeSection: string;
  homeHint: string;
  contactsSection: string;
  contactsHint: string;
  contactsTelegram: string;
  contactsDiscord: string;
  contactsEmail: string;
  newsSection: string;
  changelogSection: string;
  pollsSection: string;
  save: string;
  apply: string;
  actionOk: string;
  actionFailed: string;
  badge: string;
  titlePre: string;
  titleBrand: string;
  subtitle: string;
  newsText: string;
  newsIcon: string;
  addNews: string;
  hide: string;
  show: string;
  changelogType: string;
  changelogPlace: string;
  changelogDesc: string;
  addChangelog: string;
  delete: string;
  pollQuestion: string;
  pollDays: string;
  pollAnswers: string;
  pollAnswersHint: string;
  pollAddOption: string;
  pollRemoveOption: string;
  createPoll: string;
  active: string;
  closed: string;
  loading: string;
};

export function AdminCmsPanel({
  token,
  labels,
}: {
  token: string;
  labels: Labels;
}) {
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState("");
  const [err, setErr] = useState("");
  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");

  const [hero, setHero] = useState<Hero>({
    badge: "",
    titlePre: "",
    titleBrand: "",
    subtitle: "",
  });
  // BEGIN CHANGE: contatos editaveis
  const [contacts, setContacts] = useState({ telegram: "", discord: "", email: "" });
  // END CHANGE
  const [news, setNews] = useState<NewsRow[]>([]);
  const [changelog, setChangelog] = useState<ChangelogRow[]>([]);
  const [polls, setPolls] = useState<PollRow[]>([]);

  const [newsText, setNewsText] = useState("");
  const [newsIcon, setNewsIcon] = useState("0");
  // BEGIN CHANGE: item 9 - edicao inline de news
  const [editKey, setEditKey] = useState<string | null>(null);
  const [editText, setEditText] = useState("");
  const [editIcon, setEditIcon] = useState("0");
  // END CHANGE
  const [clType, setClType] = useState("update");
  const [clPlace, setClPlace] = useState("server");
  const [clDesc, setClDesc] = useState("");
  const [pollQ, setPollQ] = useState("");
  const [pollDays, setPollDays] = useState("7");
  const [pollOptions, setPollOptions] = useState<string[]>(["Sim", "Nao"]);

  function load() {
    setStatus("loading");
    fetch(apiUrl("portal-cms.php"), { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json) => {
        if (json.hero) setHero(json.hero);
        if (json.contacts) {
          setContacts({
            telegram: json.contacts.telegram || "",
            discord: json.contacts.discord || "",
            email: json.contacts.email || "",
          });
        }
        setNews(json.news ?? []);
        setChangelog(json.changelog ?? []);
        setPolls(json.polls ?? []);
        setStatus("ok");
      })
      .catch(() => setStatus("error"));
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [token]);

  async function post(body: Record<string, unknown>) {
    setBusy(true);
    setMsg("");
    setErr("");
    try {
      const r = await fetch(apiUrl("portal-cms.php"), {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(body),
      });
      const json = await r.json().catch(() => ({}));
      if (!r.ok) {
        setErr(json.error || labels.actionFailed);
        return;
      }
      if (json.hero) setHero(json.hero);
      if (json.contacts) {
        setContacts({
          telegram: json.contacts.telegram || "",
          discord: json.contacts.discord || "",
          email: json.contacts.email || "",
        });
      }
      if (json.news) setNews(json.news);
      if (json.changelog) setChangelog(json.changelog);
      if (json.polls) setPolls(json.polls);
      setMsg(labels.actionOk);
    } catch {
      setErr(labels.actionFailed);
    } finally {
      setBusy(false);
    }
  }

  function fmt(ts: number) {
    if (!ts) return "-";
    return new Date(ts * 1000).toLocaleString();
  }

  async function saveHero(e: FormEvent) {
    e.preventDefault();
    await post({
      action: "set_hero",
      badge: hero.badge,
      titlePre: hero.titlePre,
      titleBrand: hero.titleBrand,
      subtitle: hero.subtitle,
    });
  }

  // BEGIN CHANGE
  async function saveContacts(e: FormEvent) {
    e.preventDefault();
    await post({
      action: "set_contacts",
      telegram: contacts.telegram,
      discord: contacts.discord,
      email: contacts.email,
    });
  }
  // END CHANGE

  if (status === "loading") {
    return <p className="mt-6 text-sm text-muted">{labels.loading}</p>;
  }
  if (status === "error") {
    return <p className="mt-6 text-sm text-muted">{labels.actionFailed}</p>;
  }

  return (
    <div className="mt-8 space-y-8">
      {msg && <p className="text-sm text-brand">{msg}</p>}
      {err && <p className="text-sm text-red-400">{err}</p>}

      {/* BEGIN CHANGE: hero CMS + preview da arte fixa */}
      <section className="rounded-xl border border-border bg-panel p-5">
        <h2 className="text-lg font-semibold">{labels.homeSection}</h2>
        <p className="mt-1 text-sm text-muted">{labels.homeHint}</p>
        <div className="mt-4 overflow-hidden rounded-lg border border-border bg-background/40">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src="/brand-art/wa-site-hero-banner.png"
            alt=""
            className="mx-auto h-28 w-auto object-contain py-2 sm:h-36"
          />
        </div>
        <form onSubmit={saveHero} className="mt-4 grid gap-3">
          <label className="text-sm">
            <span className="text-muted">{labels.badge}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={hero.badge}
              onChange={(e) => setHero({ ...hero, badge: e.target.value })}
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">{labels.titlePre}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={hero.titlePre}
              onChange={(e) => setHero({ ...hero, titlePre: e.target.value })}
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">{labels.titleBrand}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={hero.titleBrand}
              onChange={(e) => setHero({ ...hero, titleBrand: e.target.value })}
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">{labels.subtitle}</span>
            <textarea
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              rows={3}
              value={hero.subtitle}
              onChange={(e) => setHero({ ...hero, subtitle: e.target.value })}
            />
          </label>
          <button
            type="submit"
            disabled={busy}
            className="w-fit rounded bg-brand px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
          >
            {labels.save}
          </button>
        </form>
      </section>
      {/* END CHANGE */}

      {/* BEGIN CHANGE: contatos da home */}
      <section className="rounded-xl border border-border bg-panel p-5">
        <h2 className="text-lg font-semibold">{labels.contactsSection}</h2>
        <p className="mt-1 text-sm text-muted">{labels.contactsHint}</p>
        <form onSubmit={saveContacts} className="mt-4 grid gap-3">
          <label className="text-sm">
            <span className="text-muted">{labels.contactsTelegram}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              type="url"
              placeholder="https://t.me/..."
              value={contacts.telegram}
              onChange={(e) => setContacts({ ...contacts, telegram: e.target.value })}
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">{labels.contactsDiscord}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              type="url"
              placeholder="https://discord.gg/..."
              value={contacts.discord}
              onChange={(e) => setContacts({ ...contacts, discord: e.target.value })}
            />
          </label>
          <label className="text-sm">
            <span className="text-muted">{labels.contactsEmail}</span>
            <input
              className="mt-1 w-full rounded border border-border bg-background px-3 py-2 text-sm"
              type="email"
              placeholder="staff@..."
              value={contacts.email}
              onChange={(e) => setContacts({ ...contacts, email: e.target.value })}
            />
          </label>
          <button
            type="submit"
            disabled={busy}
            className="w-fit rounded bg-brand px-4 py-2 text-sm font-medium text-white disabled:opacity-50"
          >
            {labels.save}
          </button>
        </form>
      </section>
      {/* END CHANGE */}

      <section className="rounded-xl border border-border bg-panel p-5">
        <h2 className="text-lg font-semibold">{labels.newsSection}</h2>
        <div className="mt-4 grid gap-2">
          <textarea
            className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
            rows={3}
            placeholder={labels.newsText}
            value={newsText}
            onChange={(e) => setNewsText(e.target.value)}
          />
          {/* BEGIN CHANGE: aviso - HTML permitido inclui links */}
          <p className="text-xs text-muted">
            HTML permitido: &lt;b&gt; &lt;i&gt; &lt;strong&gt; &lt;em&gt; &lt;p&gt; &lt;br&gt; &lt;ul&gt; &lt;ol&gt; &lt;li&gt; e links.
            Ex.: &lt;a href=&quot;https://site.com&quot;&gt;texto&lt;/a&gt; (abre em nova aba). So http(s), mailto ou caminho iniciando com /.
          </p>
          {/* END CHANGE */}
          <div className="flex flex-wrap items-center gap-2">
            <label className="text-sm text-muted">
              {labels.newsIcon}{" "}
              <select
                className="ml-1 rounded border border-border bg-background px-2 py-1"
                value={newsIcon}
                onChange={(e) => setNewsIcon(e.target.value)}
              >
                {[0, 1, 2, 3, 4].map((n) => (
                  <option key={n} value={n}>
                    {n}
                  </option>
                ))}
              </select>
            </label>
            <button
              type="button"
              disabled={busy}
              className="rounded bg-brand px-3 py-1.5 text-sm text-white disabled:opacity-50"
              onClick={() => {
                post({ action: "news_add", text: newsText, imageId: Number(newsIcon) });
                setNewsText("");
              }}
            >
              {labels.addNews}
            </button>
          </div>
        </div>
        <ul className="mt-4 divide-y divide-border/40">
          {news.map((n) => {
            const key = `${n.date}-${n.authorId}`;
            const editing = editKey === key;
            return (
              <li key={key} className="py-3 text-sm">
                <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted">
                  <span>
                    {fmt(n.date)} - {n.author}
                    {n.hidden ? " - hidden" : ""}
                  </span>
                  {/* BEGIN CHANGE: item 9 - editar / excluir / ocultar */}
                  <div className="flex flex-wrap gap-1.5">
                    <button
                      type="button"
                      disabled={busy}
                      className="rounded border border-border px-2 py-1 hover:border-brand disabled:opacity-50"
                      onClick={() => {
                        if (editing) {
                          setEditKey(null);
                        } else {
                          setEditKey(key);
                          setEditText(n.text);
                          setEditIcon(String(n.imageId));
                        }
                      }}
                    >
                      {editing ? "Cancelar" : "Editar"}
                    </button>
                    <button
                      type="button"
                      disabled={busy}
                      className="rounded border border-border px-2 py-1 hover:border-brand disabled:opacity-50"
                      onClick={() =>
                        post({
                          action: "news_hide",
                          date: n.date,
                          authorId: n.authorId,
                          hidden: !n.hidden,
                        })
                      }
                    >
                      {n.hidden ? labels.show : labels.hide}
                    </button>
                    <button
                      type="button"
                      disabled={busy}
                      className="rounded border border-border px-2 py-1 text-red-300 hover:border-red-400 disabled:opacity-50"
                      onClick={() => {
                        if (window.confirm("Excluir esta news definitivamente?")) {
                          post({ action: "news_delete", date: n.date, authorId: n.authorId });
                        }
                      }}
                    >
                      {labels.delete}
                    </button>
                  </div>
                  {/* END CHANGE */}
                </div>
                {editing ? (
                  /* BEGIN CHANGE: item 9 - formulario de edicao inline */
                  <div className="mt-2 grid gap-2">
                    <textarea
                      className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
                      rows={3}
                      value={editText}
                      onChange={(e) => setEditText(e.target.value)}
                    />
                    <div className="flex flex-wrap items-center gap-2">
                      <label className="text-xs text-muted">
                        {labels.newsIcon}{" "}
                        <select
                          className="ml-1 rounded border border-border bg-background px-2 py-1"
                          value={editIcon}
                          onChange={(e) => setEditIcon(e.target.value)}
                        >
                          {[0, 1, 2, 3, 4].map((v) => (
                            <option key={v} value={v}>
                              {v}
                            </option>
                          ))}
                        </select>
                      </label>
                      <button
                        type="button"
                        disabled={busy}
                        className="rounded bg-brand px-3 py-1.5 text-xs text-white disabled:opacity-50"
                        onClick={() => {
                          post({
                            action: "news_edit",
                            date: n.date,
                            authorId: n.authorId,
                            text: editText,
                            imageId: Number(editIcon),
                          });
                          setEditKey(null);
                        }}
                      >
                        {labels.save}
                      </button>
                    </div>
                  </div>
                ) : (
                  /* END CHANGE */
                  <div
                    className="mt-1 [&_a]:text-brand"
                    dangerouslySetInnerHTML={{ __html: n.text }}
                  />
                )}
              </li>
            );
          })}
        </ul>
      </section>

      <section className="rounded-xl border border-border bg-panel p-5">
        <h2 className="text-lg font-semibold">{labels.changelogSection}</h2>
        <div className="mt-4 grid gap-2 sm:grid-cols-3">
          <input
            className="rounded border border-border bg-background px-3 py-2 text-sm"
            placeholder={labels.changelogType}
            value={clType}
            onChange={(e) => setClType(e.target.value)}
          />
          <input
            className="rounded border border-border bg-background px-3 py-2 text-sm"
            placeholder={labels.changelogPlace}
            value={clPlace}
            onChange={(e) => setClPlace(e.target.value)}
          />
          <input
            className="rounded border border-border bg-background px-3 py-2 text-sm sm:col-span-3"
            placeholder={labels.changelogDesc}
            value={clDesc}
            onChange={(e) => setClDesc(e.target.value)}
          />
          <button
            type="button"
            disabled={busy}
            className="w-fit rounded bg-brand px-3 py-1.5 text-sm text-white disabled:opacity-50"
            onClick={() => {
              post({
                action: "changelog_add",
                type: clType,
                place: clPlace,
                description: clDesc,
              });
              setClDesc("");
            }}
          >
            {labels.addChangelog}
          </button>
        </div>
        <ul className="mt-4 divide-y divide-border/40">
          {changelog.map((c) => (
            <li key={c.id} className="flex flex-wrap items-start justify-between gap-2 py-3 text-sm">
              <div>
                <p className="text-xs text-muted">
                  {fmt(c.date)} - {c.type} - {c.place}
                </p>
                <p className="mt-1">{c.description}</p>
              </div>
              <button
                type="button"
                disabled={busy}
                className="rounded border border-border px-2 py-1 text-xs hover:border-red-400 disabled:opacity-50"
                onClick={() => post({ action: "changelog_delete", id: c.id })}
              >
                {labels.delete}
              </button>
            </li>
          ))}
        </ul>
      </section>

      <section className="rounded-xl border border-border bg-panel p-5">
        <h2 className="text-lg font-semibold">{labels.pollsSection}</h2>
        {/* BEGIN CHANGE: formulario de enquete com labels e opcoes estruturadas */}
        <div className="mt-4 grid gap-4">
          <label className="grid gap-1.5 text-sm">
            <span className="font-medium text-muted">{labels.pollQuestion}</span>
            <input
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={pollQ}
              onChange={(e) => setPollQ(e.target.value)}
            />
          </label>

          <label className="grid max-w-[200px] gap-1.5 text-sm">
            <span className="font-medium text-muted">{labels.pollDays}</span>
            <input
              type="number"
              min={1}
              max={365}
              className="w-full rounded border border-border bg-background px-3 py-2 text-sm"
              value={pollDays}
              onChange={(e) => setPollDays(e.target.value)}
            />
          </label>

          <div className="grid gap-2">
            <div className="flex items-center justify-between gap-2">
              <span className="text-sm font-medium text-muted">{labels.pollAnswers}</span>
              <span className="text-xs text-muted">{labels.pollAnswersHint}</span>
            </div>
            {pollOptions.map((opt, idx) => (
              <div key={idx} className="flex items-center gap-2">
                <span className="w-6 shrink-0 text-center text-xs text-muted">{idx + 1}.</span>
                <input
                  className="min-w-0 flex-1 rounded border border-border bg-background px-3 py-2 text-sm"
                  value={opt}
                  onChange={(e) => {
                    const next = [...pollOptions];
                    next[idx] = e.target.value;
                    setPollOptions(next);
                  }}
                />
                <button
                  type="button"
                  disabled={pollOptions.length <= 2 || busy}
                  className="shrink-0 rounded border border-border px-2 py-1.5 text-xs text-muted hover:border-red-400 hover:text-red-300 disabled:opacity-40"
                  onClick={() =>
                    setPollOptions(pollOptions.filter((_, i) => i !== idx))
                  }
                >
                  {labels.pollRemoveOption}
                </button>
              </div>
            ))}
            <button
              type="button"
              disabled={busy || pollOptions.length >= 10}
              className="w-fit rounded border border-border px-3 py-1.5 text-xs hover:border-brand/40 disabled:opacity-50"
              onClick={() => setPollOptions([...pollOptions, ""])}
            >
              {labels.pollAddOption}
            </button>
          </div>

          <button
            type="button"
            disabled={busy}
            className="w-fit rounded bg-brand px-3 py-1.5 text-sm text-white disabled:opacity-50"
            onClick={() => {
              const answers = pollOptions.map((s) => s.trim()).filter(Boolean);
              if (answers.length < 2) {
                setErr(labels.pollAnswersHint);
                return;
              }
              post({
                action: "poll_create",
                question: pollQ,
                days: Number(pollDays),
                answers,
              });
              setPollQ("");
              setPollDays("7");
              setPollOptions(["Sim", "Nao"]);
            }}
          >
            {labels.createPoll}
          </button>
        </div>
        {/* END CHANGE */}
        <ul className="mt-4 divide-y divide-border/40 text-sm">
          {polls.map((p) => (
            <li key={p.id} className="py-2">
              <span className="font-medium">{p.question}</span>
              <span className="ml-2 text-xs text-muted">
                #{p.id} - {p.active ? labels.active : labels.closed} - {p.votesAll} votes - ends{" "}
                {fmt(p.end)}
              </span>
            </li>
          ))}
        </ul>
      </section>
    </div>
  );
}
// END CHANGE
