"use client";

/**
 * /admin/articles (API reference: "How articles work (admin panel)").
 * - Articles: search, category, status and per-language state filters; each row shows
 *   the text state per language and whether the article is live. Archive / restore;
 *   delete only for articles never published.
 * - Categories: the filter tabs of the Thought Leadership page (add, rename per
 *   language, reorder, deactivate, delete when unused).
 */
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useEffect, useState } from "react";
import { errorMessage, getAccessToken } from "@/app/(admin)/_lib/api";
import { articleCategoriesApi, articleLangBadge, articlesApi, type ArticleCategory, type ArticleQuery, type ArticleRow } from "@/app/(admin)/_lib/articles";
import { resolveMedia } from "@/app/(admin)/_lib/cms";
import { tr, type Translations } from "@/app/(admin)/_lib/products";
import { qk, useArticleCategories, useArticles } from "@/app/(admin)/_lib/queries";
import { SAMPLE_ARTICLES, SAMPLE_CATEGORIES, addSampleArticles } from "@/app/(admin)/_lib/sampleArticles";
import { refreshSiteContent } from "@/app/(admin)/_lib/siteCache";
import { useStore } from "@/app/(admin)/_lib/store";
import { Active, ItemModal, LangTags, ListState, MoveButtons, itemBody, toForm, useActiveLangs, type ItemConfig } from "./CatalogPage";
import { Icon } from "./Icon";
import { ConfirmDialog } from "./Modal";
import { PageHeader, Seg } from "./ui";

const when = (iso: string | null) => (iso ? new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" }) : "—");

/** Clears the website's article cache (list, tabs and article pages). */
export function refreshArticlesOnSite() {
  const token = getAccessToken();
  if (token) void refreshSiteContent("articles", token).catch(() => undefined);
}

const TABS = ["Articles", "Categories"] as const;
type Tab = (typeof TABS)[number];

const ALL_ARTICLES: ArticleQuery = { page: 1, limit: 100, search: "", category: "", status: "", lang: "", state: "", sort: "slug" };

export function ArticlesList() {
  const [tab, setTab] = useState<Tab>("Articles");
  const qc = useQueryClient();
  const { toast } = useStore();
  // Every article's slug (up to 100), to know which sample articles exist already.
  const { data: everything } = useArticles(ALL_ARTICLES);
  const existing = new Set((everything?.data ?? []).map((a) => a.slug));
  const missing = everything ? SAMPLE_ARTICLES.filter((a) => !existing.has(a.slug)) : [];
  const [asking, setAsking] = useState(false);
  const [adding, setAdding] = useState(false);
  const [progress, setProgress] = useState<string | null>(null);
  /** Every article that couldn't be added, with the API's reason (the dialog stays open to show them). */
  const [failures, setFailures] = useState<string[]>([]);
  const addSamples = async () => {
    setAdding(true);
    setFailures([]);
    try {
      const r = await addSampleArticles(existing, setProgress);
      await qc.invalidateQueries({ queryKey: ["admin", "articles"] });
      if (r.failed.length) {
        setFailures(r.failed);
        toast(`Added ${r.created.length}, ${r.failed.length} failed: see the list`);
      } else {
        setAsking(false);
        toast(`Added ${r.created.length} articles as drafts${r.categories.length ? ` (and ${r.categories.length} categories)` : ""}. Review them, then publish.`);
      }
    } catch (e) {
      setFailures([errorMessage(e)]);
      toast("Stopped: see the list");
    } finally {
      setAdding(false);
      setProgress(null);
    }
  };
  return (
    <div className="page">
      <PageHeader crumb="Website" title="Articles" desc="Thought Leadership & Articles: the list on the website, its category tabs and each article page (/articles/…). Text is published per language.">
        {missing.length > 0 && (
          <button type="button" className="btn btn-outline btn-sm" disabled={adding} onClick={() => setAsking(true)} title="Create ready-written starter articles as drafts">
            <Icon name="file" size={14} />
            Add sample articles ({missing.length})
          </button>
        )}
        <Link href="/admin/articles/new" className="btn btn-primary btn-sm">
          <Icon name="plus" size={14} />
          New article
        </Link>
      </PageHeader>
      <div style={{ marginBottom: 16 }}>
        <Seg label="Articles section" options={TABS} value={tab} onChange={setTab} />
      </div>
      {tab === "Articles" ? <ArticlesTable /> : <CategoriesCard />}
      {asking && (
        <ConfirmDialog
          title="Add the sample articles?"
          confirmLabel={adding ? "Adding…" : `Add ${missing.length}`}
          busy={adding}
          onConfirm={addSamples}
          onClose={() => {
            if (adding) return;
            setAsking(false);
            setFailures([]);
          }}
        >
          These ready-written articles are created as English drafts: <b>{missing.map((a) => a.text.title).join(", ")}</b>. Their categories (
          {SAMPLE_CATEGORIES.map((c) => c.name).join(", ")}) are added when missing, and the pictures they use are copied from the website into the Media library.
          <div className="info-note" style={{ marginTop: 12 }}>
            Nothing goes live until you publish. Read them first and adjust the text to what you want to say.
          </div>
          {progress && (
            <div className="hint">
              <span className="spin dark" /> {progress}
            </div>
          )}
          {failures.length > 0 && (
            <div className="form-error" role="alert" style={{ marginTop: 12 }}>
              Not added:
              <ul style={{ margin: "6px 0 0 18px", listStyle: "disc" }}>
                {failures.map((f, i) => (
                  <li key={i} style={{ whiteSpace: "pre-line" }}>
                    {f}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </ConfirmDialog>
      )}
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Articles                                                            */
/* ------------------------------------------------------------------ */

function ArticlesTable() {
  const qc = useQueryClient();
  const { toast } = useStore();
  const langs = useActiveLangs();
  const { data: categories } = useArticleCategories();
  const [q, setQ] = useState<ArticleQuery>({ page: 1, limit: 20, search: "", category: "", status: "", lang: "en", state: "", sort: "-updatedAt" });
  const [searchText, setSearchText] = useState("");
  useEffect(() => {
    const t = setTimeout(() => setQ((p) => (p.search === searchText ? p : { ...p, search: searchText, page: 1 })), 300);
    return () => clearTimeout(t);
  }, [searchText]);
  const set = (patch: Partial<ArticleQuery>) => setQ((p) => ({ ...p, ...patch, page: patch.page ?? 1 }));
  const { data, error, isPending, isFetching, refetch } = useArticles(q);
  const rows = data?.data ?? [];
  const meta = data?.meta;
  const [busy, setBusy] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<ArticleRow | null>(null);
  const [err, setErr] = useState<string | null>(null);

  const reload = () => qc.invalidateQueries({ queryKey: qk.articles() });

  const archive = async (a: ArticleRow) => {
    setBusy(a.id);
    try {
      await articlesApi.setStatus(a.id, a.status === "archived" ? "active" : "archived");
      await reload();
      qc.removeQueries({ queryKey: qk.article(a.id) });
      refreshArticlesOnSite();
      toast(a.status === "archived" ? `${a.title} is back (shown where published)` : `${a.title} archived: off the website`);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const remove = async () => {
    if (!deleting) return;
    setBusy("del");
    setErr(null);
    try {
      await articlesApi.remove(deleting.id);
      await reload();
      toast(`Deleted ${deleting.title}`);
      setDeleting(null);
    } catch (e) {
      setErr(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const filtered = !!(q.search || q.category || q.status || q.state);

  return (
    <>
      <div className="card">
        <div className="toolbar" style={{ flexWrap: "wrap" }}>
          <div className="search">
            <Icon name="search" />
            <input placeholder="Search title or slug…" aria-label="Search articles" maxLength={100} value={searchText} onChange={(e) => setSearchText(e.target.value)} />
          </div>
          <select className="select" aria-label="Category" value={q.category} onChange={(e) => set({ category: e.target.value })}>
            <option value="">All categories</option>
            {(categories ?? []).map((c) => (
              <option key={c.id} value={c.id}>
                {tr(c.translations, "en", "name")}
              </option>
            ))}
          </select>
          <select className="select" aria-label="Status" value={q.status} onChange={(e) => set({ status: e.target.value as ArticleQuery["status"] })}>
            <option value="">Active and archived</option>
            <option value="active">Active</option>
            <option value="archived">Archived</option>
          </select>
          <select className="select" aria-label="Text state" value={q.state} onChange={(e) => set({ state: e.target.value as ArticleQuery["state"] })}>
            <option value="">Any text state</option>
            <option value="missing">Missing</option>
            <option value="draft">Draft</option>
            <option value="in_review">In review</option>
            <option value="published">Published</option>
          </select>
          {q.state && (
            <select className="select" aria-label="In language" value={q.lang} onChange={(e) => set({ lang: e.target.value })}>
              {langs.map((l) => (
                <option key={l.code} value={l.code}>
                  in {l.name}
                </option>
              ))}
            </select>
          )}
          {isFetching && !isPending && <span className="spin dark" aria-label="Updating" />}
        </div>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Article</th>
                <th>Category</th>
                <th>Languages</th>
                <th>Website</th>
                <th>Published</th>
                <th>Updated</th>
                <th>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {isPending ? (
                <tr>
                  <td className="empty" colSpan={7}>
                    <span className="spin dark" /> Loading articles…
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td className="empty" colSpan={7}>
                    {errorMessage(error)}{" "}
                    <button type="button" className="link" onClick={() => refetch()}>
                      Retry
                    </button>
                  </td>
                </tr>
              ) : rows.length === 0 ? (
                <tr>
                  <td className="empty" colSpan={7}>
                    {filtered ? (
                      "No articles match."
                    ) : (
                      <>
                        No articles yet.{" "}
                        <Link href="/admin/articles/new" className="link">
                          Write the first one
                        </Link>{" "}
                        (add its category under Categories first).
                      </>
                    )}
                  </td>
                </tr>
              ) : (
                rows.map((a) => {
                  const img = resolveMedia(a.coverImage?.url);
                  return (
                    <tr key={a.id}>
                      <td>
                        <div className="who">
                          <span className="thumb" style={{ backgroundImage: img ? `url("${img}")` : undefined, backgroundColor: "var(--bg)" }} />
                          <div style={{ minWidth: 0 }}>
                            <Link href={`/admin/articles/${a.id}`} className="link">
                              <b>{a.title || a.slug}</b>
                            </Link>
                            <div style={{ color: "var(--muted)", fontSize: 12 }}>/articles/{a.slug}</div>
                          </div>
                        </div>
                      </td>
                      <td>{a.category?.name ?? "—"}</td>
                      <td>
                        <span className="sec-tags">
                          {langs.map((l) => {
                            const s = a.languages[l.code];
                            const b = articleLangBadge(s?.status ?? "missing", !!s?.live);
                            return (
                              <span key={l.code} className={`tag ${b.tone}`} title={`${l.name}: ${b.label}${s?.live ? " (live)" : ""}`}>
                                {l.code.toUpperCase()}
                              </span>
                            );
                          })}
                        </span>
                      </td>
                      <td>{a.status === "archived" ? <span className="tag n">Archived</span> : a.live ? <span className="tag g">Live</span> : <span className="tag n">Not live</span>}</td>
                      <td style={{ color: "var(--muted)" }}>{when(a.firstPublishedAt)}</td>
                      <td style={{ color: "var(--muted)" }}>{when(a.updatedAt)}</td>
                      <td>
                        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                          <Link href={`/admin/articles/${a.id}`} className="btn btn-outline btn-sm">
                            Edit
                          </Link>
                          <button type="button" className="btn-plain" disabled={busy === a.id} onClick={() => archive(a)}>
                            {a.status === "archived" ? "Restore" : "Archive"}
                          </button>
                          {!a.firstPublishedAt && (
                            <button
                              type="button"
                              className="btn-plain danger"
                              onClick={() => {
                                setErr(null);
                                setDeleting(a);
                              }}
                            >
                              Delete
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
        {meta && meta.totalPages > 1 && (
          <div className="pager">
            <span>
              {(meta.page - 1) * meta.limit + 1}–{Math.min(meta.page * meta.limit, meta.total)} of {meta.total}
            </span>
            <div>
              <button type="button" className="btn btn-outline btn-sm" disabled={meta.page <= 1} onClick={() => set({ page: meta.page - 1 })}>
                Previous
              </button>
              <button type="button" className="btn btn-outline btn-sm" disabled={meta.page >= meta.totalPages} onClick={() => set({ page: meta.page + 1 })}>
                Next
              </button>
            </div>
          </div>
        )}
      </div>
      <p className="note">Archive takes an article off the website in every language and keeps everything. Delete is only possible for articles that were never published.</p>
      {deleting && (
        <ConfirmDialog title={`Delete ${deleting.title}?`} confirmLabel="Delete article" danger busy={busy === "del"} onConfirm={remove} onClose={() => setDeleting(null)}>
          The article and its text in every language are deleted. This can&apos;t be undone.
          {err && <div className="form-error">{err}</div>}
        </ConfirmDialog>
      )}
    </>
  );
}

/* ------------------------------------------------------------------ */
/* Categories (the website's filter tabs)                              */
/* ------------------------------------------------------------------ */

const CATEGORY: ItemConfig = { textKey: "name", textLabel: "Name", textMax: 120, description: true, active: true };
const catName = (c: ArticleCategory) => tr(c.translations as Translations<Record<string, unknown>>, "en", "name");

function CategoriesCard() {
  const qc = useQueryClient();
  const { toast } = useStore();
  const { data, error, isPending, refetch } = useArticleCategories();
  const [open, setOpen] = useState<{ item?: ArticleCategory } | null>(null);
  const [deleting, setDeleting] = useState<ArticleCategory | null>(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const items = data ?? [];
  const ids = items.map((c) => c.id);

  const after = async () => {
    await qc.invalidateQueries({ queryKey: qk.articleCategories });
    // Category names show on the cards and article pages too.
    await qc.invalidateQueries({ queryKey: qk.articles() });
    refreshArticlesOnSite();
  };
  const reorder = async (next: string[]) => {
    try {
      await articleCategoriesApi.reorder(next);
      await after();
      toast("Order saved");
    } catch (e) {
      toast(errorMessage(e));
    }
  };
  const remove = async () => {
    if (!deleting) return;
    setBusy(true);
    setErr(null);
    try {
      await articleCategoriesApi.remove(deleting.id);
      await after();
      toast(`Deleted ${catName(deleting)}`);
      setDeleting(null);
    } catch (e) {
      setErr(errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="card">
      <div className="card-h">
        <div>
          <h3>Categories</h3>
          <div className="sub">The filter tabs of the Thought Leadership page, in this order after &quot;All&quot;. Inactive categories are hidden on the website and can&apos;t be picked for new articles.</div>
        </div>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setOpen({})}>
          <Icon name="plus" size={14} />
          New category
        </button>
      </div>
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Name (English)</th>
              <th>Slug</th>
              <th>Languages</th>
              <th>Website</th>
              <th>
                <span className="sr-only">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            <ListState pending={isPending} error={error} retry={refetch} cols={5} empty={items.length ? null : "No categories yet. Add one (e.g. AI & Supply Chain) before writing an article."} />
            {items.map((c) => (
              <tr key={c.id}>
                <td>
                  <b style={{ fontWeight: 500 }}>{catName(c)}</b>
                </td>
                <td style={{ color: "var(--muted)" }}>{c.slug}</td>
                <td>
                  <LangTags t={c.translations as Translations<Record<string, unknown>>} />
                </td>
                <td>
                  <Active on={c.isActive} />
                </td>
                <td>
                  <div style={{ display: "flex", gap: 6, justifyContent: "flex-end", alignItems: "center" }}>
                    <MoveButtons ids={ids} id={c.id} label={catName(c)} onMove={reorder} />
                    <button type="button" className="btn btn-outline btn-sm" onClick={() => setOpen({ item: c })}>
                      Edit
                    </button>
                    <button
                      type="button"
                      className="btn-plain danger"
                      onClick={() => {
                        setErr(null);
                        setDeleting(c);
                      }}
                    >
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {open && (
        <ItemModal
          title={open.item ? `Edit ${catName(open.item)}` : "New category"}
          cfg={CATEGORY}
          initial={open.item ? toForm(CATEGORY, open.item as never) : undefined}
          onClose={() => setOpen(null)}
          onSubmit={async (f) => {
            if (open.item) await articleCategoriesApi.update(open.item.id, itemBody(CATEGORY, f, toForm(CATEGORY, open.item as never)));
            else await articleCategoriesApi.create(itemBody(CATEGORY, f));
            await after();
            toast(open.item ? "Saved" : "Created");
          }}
        />
      )}
      {deleting && (
        <ConfirmDialog title={`Delete ${catName(deleting)}?`} confirmLabel="Delete" danger busy={busy} onConfirm={remove} onClose={() => setDeleting(null)}>
          The tab is removed in every language. A category still used by an article (archived ones too) can&apos;t be deleted: move those articles or deactivate the category instead.
          {err && <div className="form-error">{err}</div>}
        </ConfirmDialog>
      )}
    </div>
  );
}
