import type { Metadata } from "next";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

import { softLaunchAdminCookieDigest } from "@/server/soft-launch-admin-digest";

export const runtime = "nodejs";

export const metadata: Metadata = {
  title: "Soft launch — review lá",
  robots: { index: false, follow: false },
};

type ReviewApiOverview = {
  title: string | null;
  wordCount: number | null;
  layeredSections: unknown[];
  interpretationSignals: unknown[];
  expertIntelligence: unknown;
  dominantPalaceKey: string | null;
} | null;

type ReviewBundle = {
  chartRecordId: string;
  chartFingerprint: string;
  saveScopeKey: string | null;
  createdAt: string;
  overview: ReviewApiOverview;
  prosePolish: { stitchingIssues: string[]; lowInsightSectionIds: string[] };
  note?: string;
};

export default async function SoftLaunchReviewPage({
  params,
}: {
  params: Promise<{ chartRecordId: string }>;
}) {
  const { chartRecordId } = await params;
  const envSecret = process.env.SOFT_LAUNCH_ADMIN_SECRET?.trim();
  if (!envSecret) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>Chưa cấu hình SOFT_LAUNCH_ADMIN_SECRET trên máy chủ web.</p>
      </main>
    );
  }
  const jar = await cookies();
  const token = jar.get("ctkp_sl_adm")?.value;
  if (token !== softLaunchAdminCookieDigest(envSecret)) {
    redirect(`/internal/soft-launch/login?next=${encodeURIComponent(`/internal/soft-launch/review/${chartRecordId}`)}`);
  }

  const api = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "");
  if (!api) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>Chưa cấu hình NEXT_PUBLIC_API_BASE_URL.</p>
      </main>
    );
  }

  const res = await fetch(`${api}/soft-launch/admin/review/${chartRecordId}`, {
    headers: { "X-Soft-Launch-Admin-Secret": envSecret },
    cache: "no-store",
  });

  if (res.status === 401 || res.status === 403) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>Backend từ chối (401/403) — kiểm tra SOFT_LAUNCH_ADMIN_SECRET trùng giữa web và API.</p>
      </main>
    );
  }

  if (!res.ok) {
    return (
      <main className="min-h-[50dvh] bg-stone-950 p-8 text-stone-200">
        <p>
          Lỗi {res.status} khi gọi review — kiểm tra UUID và migration soft launch trên DB.
        </p>
      </main>
    );
  }

  const bundle = (await res.json()) as ReviewBundle;
  const ov = bundle.overview;
  const eil = ov?.expertIntelligence && typeof ov.expertIntelligence === "object" ? ov.expertIntelligence : null;

  return (
    <main className="min-h-[100dvh] bg-stone-950 px-4 py-10 text-stone-100">
      <div className="mx-auto max-w-4xl space-y-8 font-sans text-sm">
        <header className="space-y-1 border-b border-stone-800 pb-4">
          <h1 className="text-xl text-stone-50">Review lá (nội bộ)</h1>
          <p className="text-xs text-stone-500">
            <span className="text-stone-400">chartRecordId</span> {bundle.chartRecordId} ·{" "}
            <span className="text-stone-400">fingerprint</span> {bundle.chartFingerprint}
          </p>
          <p className="text-xs text-stone-500">createdAt {bundle.createdAt}</p>
          {bundle.note ? <p className="text-amber-200/90">{bundle.note}</p> : null}
        </header>

        <section className="space-y-2">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-stone-400">Cảnh báo prose</h2>
          <ul className="list-disc space-y-1 pl-5 text-stone-300">
            {bundle.prosePolish.stitchingIssues?.length ?
              bundle.prosePolish.stitchingIssues.map((s, i) => <li key={`s-${i}`}>{s}</li>)
            : <li className="text-stone-500">Không có stitchingIssues.</li>}
          </ul>
          <p className="text-stone-400">
            Low insight sections: {(bundle.prosePolish.lowInsightSectionIds ?? []).join(", ") || "—"}
          </p>
        </section>

        <section className="space-y-2">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-stone-400">Tổng quan</h2>
          <p className="text-stone-300">
            Title: {ov?.title ?? "—"} · wordCount: {ov?.wordCount ?? "—"} · dominantPalaceKey:{" "}
            {ov?.dominantPalaceKey ?? "—"}
          </p>
          <h3 className="text-xs uppercase text-stone-500">layeredSections (tiêu đề)</h3>
          <ol className="list-decimal space-y-1 pl-5 text-stone-300">
            {(ov?.layeredSections ?? []).map((row, i) => (
              <li key={i}>
                {typeof row === "object" && row && "title" in row ? String((row as { title?: string }).title) : JSON.stringify(row)}
              </li>
            ))}
          </ol>
        </section>

        <section className="space-y-2">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-stone-400">interpretationSignals</h2>
          <pre className="max-h-[320px] overflow-auto rounded border border-stone-800 bg-stone-900/80 p-3 text-[11px] leading-relaxed text-emerald-100/90">
            {JSON.stringify(ov?.interpretationSignals ?? [], null, 2)}
          </pre>
        </section>

        <section className="space-y-2">
          <h2 className="text-sm font-semibold uppercase tracking-wide text-stone-400">EIL / expertIntelligence (rút gọn)</h2>
          <pre className="max-h-[480px] overflow-auto rounded border border-stone-800 bg-stone-900/80 p-3 text-[11px] leading-relaxed text-violet-100/90">
            {eil ? JSON.stringify(eil, null, 2).slice(0, 24_000) : "null"}
            {eil && JSON.stringify(eil, null, 2).length > 24_000 ? "\n… (truncated)" : ""}
          </pre>
        </section>
      </div>
    </main>
  );
}
