import Link from "next/link";
import { prisma } from "@/lib/db";
import { ReanalyzeButton } from "./_reanalyze-button";

export const dynamic = "force-dynamic";

function fmt(n: number): string {
  return n.toLocaleString("vi-VN");
}

function pct(part: number, total: number): string {
  if (total === 0) return "0%";
  return `${Math.round((part / total) * 100)}%`;
}

export default async function SeoAdminPage() {
  // Aggregate stats
  const [
    total,
    published,
    missingMetaTitle,
    missingMetaDesc,
    missingFocusKw,
    missingCover,
    lowSeoScore,
    lowReadability,
    avgSeo,
    avgRead,
    worstSeo,
    recentBest,
  ] = await Promise.all([
    prisma.article.count(),
    prisma.article.count({ where: { status: "published" } }),
    prisma.article.count({
      where: { OR: [{ metaTitle: null }, { metaTitle: "" }] },
    }),
    prisma.article.count({
      where: { OR: [{ metaDesc: null }, { metaDesc: "" }] },
    }),
    prisma.article.count({
      where: { OR: [{ focusKeyword: null }, { focusKeyword: "" }] },
    }),
    prisma.article.count({
      where: { OR: [{ coverImage: null }, { coverImage: "" }] },
    }),
    prisma.article.count({
      where: { status: "published", seoScore: { lt: 70 } },
    }),
    prisma.article.count({
      where: { status: "published", readabilityScore: { lt: 60 } },
    }),
    prisma.article.aggregate({
      where: { status: "published" },
      _avg: { seoScore: true },
    }),
    prisma.article.aggregate({
      where: { status: "published" },
      _avg: { readabilityScore: true },
    }),
    prisma.article.findMany({
      where: { status: "published" },
      orderBy: { seoScore: "asc" },
      take: 10,
      select: {
        id: true,
        slug: true,
        title: true,
        seoScore: true,
        readabilityScore: true,
        metaTitle: true,
        metaDesc: true,
        focusKeyword: true,
        coverImage: true,
      },
    }),
    prisma.article.findMany({
      where: { status: "published", seoScore: { gte: 80 } },
      orderBy: { publishedAt: "desc" },
      take: 5,
      select: { id: true, slug: true, title: true, seoScore: true },
    }),
  ]);

  const stats: Array<{ label: string; value: string; sub?: string; tone: string }> = [
    {
      label: "Bài đã publish",
      value: fmt(published),
      sub: `${pct(published, total)} của ${fmt(total)} bài`,
      tone: "text-emerald-300",
    },
    {
      label: "SEO score TB",
      value: avgSeo._avg.seoScore != null ? avgSeo._avg.seoScore.toFixed(1) : "—",
      sub: `${fmt(lowSeoScore)} bài < 70 điểm`,
      tone: lowSeoScore > 0 ? "text-amber-300" : "text-emerald-300",
    },
    {
      label: "Readability TB",
      value: avgRead._avg.readabilityScore != null ? avgRead._avg.readabilityScore.toFixed(1) : "—",
      sub: `${fmt(lowReadability)} bài < 60 điểm`,
      tone: lowReadability > 0 ? "text-amber-300" : "text-emerald-300",
    },
    {
      label: "Thiếu meta title",
      value: fmt(missingMetaTitle),
      sub: pct(missingMetaTitle, total),
      tone: missingMetaTitle > 0 ? "text-rose-300" : "text-emerald-300",
    },
    {
      label: "Thiếu meta desc",
      value: fmt(missingMetaDesc),
      sub: pct(missingMetaDesc, total),
      tone: missingMetaDesc > 0 ? "text-rose-300" : "text-emerald-300",
    },
    {
      label: "Thiếu focus keyword",
      value: fmt(missingFocusKw),
      sub: pct(missingFocusKw, total),
      tone: missingFocusKw > 0 ? "text-amber-300" : "text-emerald-300",
    },
    {
      label: "Thiếu cover image",
      value: fmt(missingCover),
      sub: pct(missingCover, total),
      tone: missingCover > 0 ? "text-amber-300" : "text-emerald-300",
    },
  ];

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">SEO Health</h1>
        <p className="text-sm text-ink-muted">
          Tổng quan sức khỏe SEO toàn site. Số liệu tính lại mỗi lần load.
        </p>
      </div>

      <ReanalyzeButton />

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-8">
        {stats.map((s) => (
          <div
            key={s.label}
            className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4"
          >
            <div className="text-xs text-ink-muted">{s.label}</div>
            <div className={`text-2xl font-display font-bold mt-1 ${s.tone}`}>{s.value}</div>
            {s.sub && <div className="text-[11px] text-ink-muted/70 mt-0.5">{s.sub}</div>}
          </div>
        ))}
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        <section className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden">
          <div className="px-4 py-3 border-b border-stroke-subtle bg-bg-elevated/40">
            <h2 className="font-display font-semibold">10 bài SEO yếu nhất</h2>
            <p className="text-xs text-ink-muted mt-0.5">Cần ưu tiên tối ưu để leo SERP</p>
          </div>
          {worstSeo.length === 0 ? (
            <div className="p-6 text-center text-sm text-ink-muted">Chưa có bài published nào.</div>
          ) : (
            <ul className="divide-y divide-stroke-subtle/60">
              {worstSeo.map((a) => {
                const issues: string[] = [];
                if (!a.metaTitle) issues.push("meta title");
                if (!a.metaDesc) issues.push("meta desc");
                if (!a.focusKeyword) issues.push("focus kw");
                if (!a.coverImage) issues.push("cover");
                return (
                  <li key={a.id} className="px-4 py-3 hover:bg-bg-overlay/40 transition">
                    <Link href={`/admin/articles/${a.id}`} className="block">
                      <div className="flex items-start gap-3">
                        <span
                          className={`shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-full text-xs font-bold ${
                            (a.seoScore ?? 0) >= 70
                              ? "bg-emerald-500/15 text-emerald-300"
                              : (a.seoScore ?? 0) >= 50
                                ? "bg-amber-500/15 text-amber-300"
                                : "bg-rose-500/15 text-rose-300"
                          }`}
                        >
                          {a.seoScore ?? 0}
                        </span>
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-medium line-clamp-1">{a.title}</div>
                          <div className="text-[11px] text-ink-muted mt-0.5">
                            {issues.length > 0 ? (
                              <span className="text-rose-300">Thiếu: {issues.join(", ")}</span>
                            ) : (
                              "Cần cải thiện score"
                            )}
                          </div>
                        </div>
                      </div>
                    </Link>
                  </li>
                );
              })}
            </ul>
          )}
        </section>

        <section className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden">
          <div className="px-4 py-3 border-b border-stroke-subtle bg-bg-elevated/40">
            <h2 className="font-display font-semibold">Bài tốt gần đây</h2>
            <p className="text-xs text-ink-muted mt-0.5">SEO score ≥ 80, mới publish</p>
          </div>
          {recentBest.length === 0 ? (
            <div className="p-6 text-center text-sm text-ink-muted">
              Chưa có bài nào đạt 80+ điểm. Tối ưu meta + focus keyword để cải thiện.
            </div>
          ) : (
            <ul className="divide-y divide-stroke-subtle/60">
              {recentBest.map((a) => (
                <li key={a.id} className="px-4 py-3 hover:bg-bg-overlay/40 transition">
                  <Link href={`/admin/articles/${a.id}`} className="block flex items-center gap-3">
                    <span className="shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-full text-xs font-bold bg-emerald-500/15 text-emerald-300">
                      {a.seoScore}
                    </span>
                    <div className="flex-1 min-w-0">
                      <div className="text-sm font-medium line-clamp-1">{a.title}</div>
                      <div className="text-[11px] text-ink-muted mt-0.5 font-mono">/{a.slug}</div>
                    </div>
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </section>
      </div>
    </div>
  );
}
