"use client";

import { useEffect, useState } from "react";

type NarrativeRecent = {
  id: string;
  generatedAt: string;
  region: { nameSr: string; slug: string; type: string };
  category: { nameSr: string; slug: string };
};

type QuestionRecent = {
  slug: string;
  question: string;
  createdAt: string;
  status: string;
};

type MagazineTopic = {
  template: string;
  categorySlug: string;
  categoryName: string;
  regionSlug?: string;
  regionName?: string;
  proposedTitle: string;
};

type State = {
  narrativeTotal: number;
  narrativeRecent: NarrativeRecent[];
  questionTotal: number;
  questionRecent: QuestionRecent[];
  magazineTopics: MagazineTopic[];
  indexNowConfigured: boolean;
};

export function SeoControlCenter() {
  const [state, setState] = useState<State | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [log, setLog] = useState<string[]>([]);

  function addLog(line: string) {
    setLog((prev) => [`[${new Date().toLocaleTimeString("sr-RS")}] ${line}`, ...prev].slice(0, 20));
  }

  async function refresh() {
    try {
      const [narr, qa, mag, idx] = await Promise.all([
        fetch("/api/admin/seo/narratives").then((r) => r.json()),
        fetch("/api/admin/seo/questions").then((r) => r.json()),
        fetch("/api/admin/seo/magazine?limit=20").then((r) => r.json()),
        fetch("/api/admin/seo/indexnow").then((r) => r.json()),
      ]);
      setState({
        narrativeTotal: narr.total ?? 0,
        narrativeRecent: narr.recent ?? [],
        questionTotal: qa.total ?? 0,
        questionRecent: qa.recent ?? [],
        magazineTopics: mag.items ?? [],
        indexNowConfigured: Boolean(idx.configured),
      });
    } catch {
      /* noop */
    }
  }

  useEffect(() => {
    void refresh();
  }, []);

  async function generateNarrativesBatch(limit: number) {
    setBusy(`narratives:${limit}`);
    try {
      const res = await fetch("/api/admin/seo/narratives", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ limit, force: false }),
      });
      const data = await res.json();
      addLog(
        `Narativi (batch ${limit}): generated=${data.generated ?? 0}, skipped=${
          data.skipped ?? 0
        }, errors=${data.errors ?? 0}`,
      );
      await refresh();
    } catch (err) {
      addLog(`GREŠKA narativi: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setBusy(null);
    }
  }

  async function generateQuestionsBatch(limit: number) {
    setBusy(`questions:${limit}`);
    try {
      const res = await fetch("/api/admin/seo/questions", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ limit }),
      });
      const data = await res.json();
      addLog(`Pitanja (batch ${limit}): generated=${data.generated ?? 0}, errors=${data.errors ?? 0}`);
      await refresh();
    } catch (err) {
      addLog(`GREŠKA pitanja: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setBusy(null);
    }
  }

  async function generateMagazine(topic: MagazineTopic) {
    setBusy(`magazine:${topic.categorySlug}:${topic.regionSlug ?? ""}`);
    try {
      const res = await fetch("/api/admin/seo/magazine", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          template: topic.template,
          categorySlug: topic.categorySlug,
          regionSlug: topic.regionSlug,
          publishImmediately: false,
        }),
      });
      const data = await res.json();
      if (data.slug) {
        addLog(`Članak generisan kao DRAFT: ${data.slug}`);
      } else {
        addLog(`Generisanje članka nije uspelo (${data.error ?? "unknown"})`);
      }
      await refresh();
    } catch (err) {
      addLog(`GREŠKA članak: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setBusy(null);
    }
  }

  if (!state) {
    return (
      <p className="p-6 text-center text-sm text-muted-foreground">Učitavam SEO podatke...</p>
    );
  }

  return (
    <div className="space-y-6">
      {/* Status row */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label="AI Narativi" value={state.narrativeTotal.toLocaleString("sr-RS")} hint="Region × Kategorija kombinacije" />
        <StatCard label="SEO Pitanja" value={state.questionTotal.toLocaleString("sr-RS")} hint="People Also Ask landings" />
        <StatCard
          label="IndexNow"
          value={state.indexNowConfigured ? "✓ Aktivno" : "✗ Nije podešeno"}
          hint="Instant discovery (Bing/Yandex)"
          tone={state.indexNowConfigured ? "good" : "warn"}
        />
        <StatCard label="Magazine predlozi" value={state.magazineTopics.length.toString()} hint="Spreman za generisanje" />
      </div>

      {/* Narratives */}
      <section className="rounded-2xl border border-border bg-white p-6">
        <h3 className="font-display text-lg font-semibold text-foreground">AI Narativi za kombo strane</h3>
        <p className="mt-1 text-sm text-muted-foreground">
          Generiše jedinstven lokalni paragraf 200-400 reči za svaku (region × kategorija) kombinaciju koja ima objavljene profile. Bez ovoga Google odbacuje kombo strane kao &bdquo;thin content&ldquo;.
        </p>
        <div className="mt-4 flex flex-wrap gap-2">
          <ActionButton onClick={() => generateNarrativesBatch(50)} busy={busy === "narratives:50"}>
            Generiši 50
          </ActionButton>
          <ActionButton onClick={() => generateNarrativesBatch(200)} busy={busy === "narratives:200"}>
            Generiši 200
          </ActionButton>
          <ActionButton onClick={() => generateNarrativesBatch(500)} busy={busy === "narratives:500"}>
            Generiši 500
          </ActionButton>
        </div>
        {state.narrativeRecent.length > 0 && (
          <div className="mt-6">
            <p className="eyebrow">Najnoviji</p>
            <ul className="mt-3 space-y-1.5 text-sm text-foreground/80">
              {state.narrativeRecent.map((n) => (
                <li key={n.id}>
                  <span className="font-semibold">{n.category.nameSr}</span>
                  <span className="mx-1.5 text-muted-foreground">×</span>
                  <span>{n.region.nameSr}</span>
                  <span className="ml-2 text-xs text-muted-foreground">
                    {new Date(n.generatedAt).toLocaleString("sr-RS")}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        )}
      </section>

      {/* Q&A */}
      <section className="rounded-2xl border border-border bg-white p-6">
        <h3 className="font-display text-lg font-semibold text-foreground">Pitanja & Odgovori (PAA capture)</h3>
        <p className="mt-1 text-sm text-muted-foreground">
          Generiše landing strane sa FAQPage schema-om koje ulaze u Google &bdquo;People Also Ask&ldquo; box. Visok CTR (40-60%) za #1 pozicije.
        </p>
        <div className="mt-4 flex flex-wrap gap-2">
          <ActionButton onClick={() => generateQuestionsBatch(10)} busy={busy === "questions:10"}>
            Generiši 10
          </ActionButton>
          <ActionButton onClick={() => generateQuestionsBatch(30)} busy={busy === "questions:30"}>
            Generiši 30
          </ActionButton>
          <ActionButton onClick={() => generateQuestionsBatch(60)} busy={busy === "questions:60"}>
            Generiši 60
          </ActionButton>
        </div>
        {state.questionRecent.length > 0 && (
          <div className="mt-6">
            <p className="eyebrow">Najnoviji</p>
            <ul className="mt-3 space-y-1.5 text-sm text-foreground/80">
              {state.questionRecent.map((q) => (
                <li key={q.slug}>
                  <a
                    href={`/pitanja/${q.slug}`}
                    target="_blank"
                    rel="noreferrer"
                    className="text-primary hover:underline"
                  >
                    {q.question}
                  </a>
                </li>
              ))}
            </ul>
          </div>
        )}
      </section>

      {/* Magazine */}
      <section className="rounded-2xl border border-border bg-white p-6">
        <h3 className="font-display text-lg font-semibold text-foreground">Magazin programmatic</h3>
        <p className="mt-1 text-sm text-muted-foreground">
          Generiše dugačak SEO članak (700-1000 reči) iz odabranog template-a. Štampa se kao DRAFT — pregledaš pre objave.
        </p>
        {state.magazineTopics.length > 0 && (
          <div className="mt-4 max-h-80 overflow-y-auto rounded-xl border border-border">
            <ul className="divide-y divide-border">
              {state.magazineTopics.map((topic, idx) => (
                <li key={idx} className="flex items-center justify-between gap-3 p-3 text-sm">
                  <span className="min-w-0 flex-1 truncate">{topic.proposedTitle}</span>
                  <button
                    type="button"
                    disabled={
                      busy === `magazine:${topic.categorySlug}:${topic.regionSlug ?? ""}`
                    }
                    onClick={() => generateMagazine(topic)}
                    className="shrink-0 rounded-lg bg-primary px-3 py-1.5 text-xs font-bold text-primary-foreground transition hover:bg-primary/90 disabled:opacity-50"
                  >
                    {busy === `magazine:${topic.categorySlug}:${topic.regionSlug ?? ""}`
                      ? "Generišem..."
                      : "Generiši"}
                  </button>
                </li>
              ))}
            </ul>
          </div>
        )}
      </section>

      {/* Log */}
      {log.length > 0 && (
        <section className="rounded-2xl border border-border bg-zinc-950 p-6 text-zinc-100">
          <p className="eyebrow text-zinc-400">Konzola</p>
          <pre className="mt-3 max-h-60 overflow-y-auto font-mono text-xs leading-6">
            {log.join("\n")}
          </pre>
        </section>
      )}
    </div>
  );
}

function StatCard({
  label,
  value,
  hint,
  tone,
}: {
  label: string;
  value: string;
  hint: string;
  tone?: "good" | "warn";
}) {
  return (
    <div
      className={`rounded-2xl border bg-white p-5 ${
        tone === "warn"
          ? "border-amber-300 bg-amber-50"
          : tone === "good"
            ? "border-emerald-300 bg-emerald-50"
            : "border-border"
      }`}
    >
      <p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
        {label}
      </p>
      <p className="mt-3 font-display text-3xl font-bold text-foreground">{value}</p>
      <p className="mt-1 text-xs text-muted-foreground">{hint}</p>
    </div>
  );
}

function ActionButton({
  onClick,
  busy,
  children,
}: {
  onClick: () => void;
  busy: boolean;
  children: React.ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={busy}
      className="rounded-lg bg-primary px-4 py-2 text-sm font-bold text-primary-foreground transition hover:bg-primary/90 disabled:opacity-50"
    >
      {busy ? "Generišem..." : children}
    </button>
  );
}
