import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useMutation, useQueryClient, useSuspenseQuery } from "@tanstack/react-query";
import { Suspense, useState } from "react";
import {
  getTopicStats,
  syncTopicCatalog,
  syncAllTopicContent,
  syncTopicContent,
} from "@/lib/api/topics-registry.functions";
import { LoadingState } from "@/components/devotional/States";
import { pageSeo } from "@/lib/seo";

const statsQuery = queryOptions({
  queryKey: ["topic-stats"],
  queryFn: () => getTopicStats(),
  staleTime: 30_000,
});

export const Route = createFileRoute("/admin/topics")({
  head: () => {
    const seo = pageSeo({
      title: "Topic Registry · Admin",
      description: "Internal topic registry diagnostics.",
      path: "/admin/topics",
      noindex: true,
    });
    return { meta: seo.meta, links: seo.links };
  },
  loader: ({ context }) => context.queryClient.ensureQueryData(statsQuery),
  component: AdminTopics,
});

function AdminTopics() {
  return (
    <div className="mx-auto max-w-6xl px-4 py-14 sm:px-6">
      <header>
        <p className="text-xs font-medium uppercase tracking-[0.2em] text-[var(--gold)]">Internal</p>
        <h1 className="mt-2 font-serif text-3xl font-semibold text-primary sm:text-4xl">
          Topic Registry Diagnostics
        </h1>
        <p className="mt-2 text-sm text-muted-foreground">
          Counts come from <code>public.topics</code>. Sync actions populate the registry and per-topic devotional cache.
        </p>
      </header>
      <Suspense fallback={<LoadingState />}>
        <StatsView />
      </Suspense>
    </div>
  );
}

function StatsView() {
  const { data } = useSuspenseQuery(statsQuery);
  const qc = useQueryClient();
  const [log, setLog] = useState<string[]>([]);
  const append = (line: string) => setLog((l) => [line, ...l].slice(0, 50));

  const catalogSync = useMutation({
    mutationFn: () => syncTopicCatalog(),
    onSuccess: (r) => { append(`catalog sync: ${JSON.stringify(r)}`); qc.invalidateQueries({ queryKey: ["topic-stats"] }); },
  });
  const batchSync = useMutation({
    mutationFn: (limit: number) => syncAllTopicContent({ data: { limit } }),
    onSuccess: (r) => { append(`batch sync: ${JSON.stringify(r)}`); qc.invalidateQueries({ queryKey: ["topic-stats"] }); },
  });
  const oneSync = useMutation({
    mutationFn: (slug: string) => syncTopicContent({ data: { slug } }),
    onSuccess: (r) => { append(`single sync: ${JSON.stringify(r)}`); qc.invalidateQueries({ queryKey: ["topic-stats"] }); },
  });

  const stat = (label: string, value: number) => (
    <div className="rounded-xl border border-border bg-card p-4">
      <div className="text-xs uppercase tracking-wide text-muted-foreground">{label}</div>
      <div className="mt-1 font-serif text-2xl text-primary">{value}</div>
    </div>
  );

  return (
    <div className="mt-8 space-y-8">
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
        {stat("Canonical topics", data.totalCanonical)}
        {stat("Aliases merged", data.totalAliases)}
        {stat("Indexable", data.indexableCount)}
        {stat("Non-indexable", data.nonIndexableCount)}
        {stat("Zero results", data.zeroResultsCount)}
        {stat("Never fetched", data.neverFetchedCount)}
      </div>

      <div className="flex flex-wrap gap-2">
        <button
          onClick={() => catalogSync.mutate()}
          disabled={catalogSync.isPending}
          className="rounded-full bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50"
        >
          {catalogSync.isPending ? "Syncing catalog…" : "Sync catalog from API"}
        </button>
        <button
          onClick={() => batchSync.mutate(10)}
          disabled={batchSync.isPending}
          className="rounded-full border border-border px-4 py-2 text-sm font-medium hover:bg-muted disabled:opacity-50"
        >
          {batchSync.isPending ? "Syncing…" : "Sync next 10 stale topics"}
        </button>
        <button
          onClick={() => batchSync.mutate(50)}
          disabled={batchSync.isPending}
          className="rounded-full border border-border px-4 py-2 text-sm font-medium hover:bg-muted disabled:opacity-50"
        >
          Sync next 50
        </button>
      </div>

      {log.length > 0 && (
        <pre className="max-h-48 overflow-auto rounded-lg border border-border bg-muted p-3 text-xs">
{log.join("\n")}
        </pre>
      )}

      <div>
        <h2 className="font-serif text-xl font-semibold text-primary">Top topics</h2>
        <div className="mt-3 overflow-x-auto">
          <table className="w-full text-left text-sm">
            <thead className="text-xs uppercase text-muted-foreground">
              <tr>
                <th className="py-2 pr-3">Display name</th>
                <th className="py-2 pr-3">Slug</th>
                <th className="py-2 pr-3">API topic</th>
                <th className="py-2 pr-3">Results</th>
                <th className="py-2 pr-3">Aliases</th>
                <th className="py-2 pr-3">Indexable</th>
                <th className="py-2 pr-3">Last fetched</th>
                <th className="py-2 pr-3">Action</th>
              </tr>
            </thead>
            <tbody>
              {data.topRows.map((r) => (
                <tr key={r.slug} className="border-t border-border">
                  <td className="py-2 pr-3">{r.display_name}</td>
                  <td className="py-2 pr-3 font-mono text-xs">{r.slug}</td>
                  <td className="py-2 pr-3 text-xs text-muted-foreground">{r.canonical_api_topic}</td>
                  <td className="py-2 pr-3">{r.result_count}</td>
                  <td className="py-2 pr-3">{r.alias_count}</td>
                  <td className="py-2 pr-3">{r.is_indexable ? "yes" : "no"}</td>
                  <td className="py-2 pr-3 text-xs">{r.last_fetched_at ? r.last_fetched_at.slice(0, 16).replace("T", " ") : "—"}</td>
                  <td className="py-2 pr-3">
                    <button
                      onClick={() => oneSync.mutate(r.slug)}
                      disabled={oneSync.isPending}
                      className="rounded border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50"
                    >
                      Sync
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
