import Link from "next/link";
import { prisma } from "@/lib/db";
import { Image as ImageIcon, ExternalLink, AlertTriangle } from "lucide-react";

export const dynamic = "force-dynamic";

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

export default async function ImageSeoPage() {
  const [
    totalMedia,
    missingAltCount,
    aiAltCount,
    contextAltCount,
    filenameAltCount,
    overrideAltCount,
    recentMissing,
    sampleByCategory,
  ] = await Promise.all([
    prisma.media.count(),
    prisma.media.count({ where: { OR: [{ alt: null }, { alt: "" }] } }),
    prisma.media.count({ where: { altSource: "ai" } }),
    prisma.media.count({ where: { altSource: "context" } }),
    prisma.media.count({ where: { altSource: "filename" } }),
    prisma.media.count({ where: { altSource: "override" } }),
    prisma.media.findMany({
      where: { OR: [{ alt: null }, { alt: "" }] },
      orderBy: { createdAt: "desc" },
      take: 12,
      select: {
        id: true,
        url: true,
        filename: true,
        createdAt: true,
      },
    }),
    prisma.$queryRaw<Array<{ source: string | null; n: bigint }>>`
      SELECT "altSource" AS source, COUNT(*) AS n
      FROM "Media"
      GROUP BY "altSource"
      ORDER BY n DESC
    `,
  ]);

  const altCoverage =
    totalMedia === 0
      ? 100
      : Math.round(((totalMedia - missingAltCount) / totalMedia) * 100);

  const cards = [
    {
      label: "Tổng số ảnh",
      value: fmt(totalMedia),
      tone: "text-ink-secondary",
    },
    {
      label: "Ảnh có alt",
      value: fmt(totalMedia - missingAltCount),
      sub: `${altCoverage}% coverage`,
      tone: altCoverage >= 95 ? "text-emerald-300" : altCoverage >= 80 ? "text-amber-300" : "text-rose-300",
    },
    {
      label: "Ảnh thiếu alt",
      value: fmt(missingAltCount),
      sub: missingAltCount > 0 ? "Cần xử lý" : "Hoàn hảo",
      tone: missingAltCount > 0 ? "text-amber-300" : "text-emerald-300",
    },
    {
      label: "Alt do AI sinh",
      value: fmt(aiAltCount),
      tone: "text-violet-300",
    },
    {
      label: "Alt từ context",
      value: fmt(contextAltCount),
      tone: "text-cyan-300",
    },
    {
      label: "Alt từ filename",
      value: fmt(filenameAltCount),
      tone: "text-emerald-300/80",
    },
    {
      label: "Alt do user nhập",
      value: fmt(overrideAltCount),
      tone: "text-emerald-300",
    },
  ];

  return (
    <div>
      <div className="mb-6">
        <h2 className="font-display font-semibold text-lg mb-1">Image SEO</h2>
        <p className="text-sm text-ink-muted">
          Theo dõi alt text coverage, phân loại nguồn alt (AI / context / filename / user
          override). Bulk action xử lý ảnh thiếu alt nằm ở{" "}
          <Link href="/admin/media" className="text-accent-primary hover:underline">
            /admin/media
          </Link>
          .
        </p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
        {cards.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 mb-6">
        <section className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4">
          <h3 className="font-medium mb-3 flex items-center gap-2">
            <ImageIcon className="h-4 w-4 text-accent-primary" />
            Phân bổ theo nguồn alt
          </h3>
          <ul className="space-y-2">
            {sampleByCategory.map((row) => {
              const n = Number(row.n);
              const pct = totalMedia > 0 ? Math.round((n / totalMedia) * 100) : 0;
              const label = row.source ?? "(chưa có alt)";
              return (
                <li key={label}>
                  <div className="flex items-center justify-between text-xs mb-1">
                    <span className="font-mono">{label}</span>
                    <span className="text-ink-muted">
                      {fmt(n)} · {pct}%
                    </span>
                  </div>
                  <div className="h-2 rounded-full bg-bg-overlay overflow-hidden">
                    <div
                      className={`h-full ${
                        label === "ai"
                          ? "bg-violet-500"
                          : label === "context"
                            ? "bg-cyan-500"
                            : label === "filename"
                              ? "bg-emerald-500/70"
                              : label === "override"
                                ? "bg-emerald-500"
                                : "bg-rose-500/60"
                      }`}
                      style={{ width: `${pct}%` }}
                    />
                  </div>
                </li>
              );
            })}
          </ul>
        </section>

        <section className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4">
          <h3 className="font-medium mb-2 flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-amber-300" />
            Ảnh mới upload thiếu alt
          </h3>
          <p className="text-xs text-ink-muted mb-3">
            12 ảnh gần nhất chưa có alt text — bấm để xử lý.
          </p>
          {recentMissing.length === 0 ? (
            <p className="text-xs text-emerald-300">
              ✓ Tất cả ảnh đã có alt text.
            </p>
          ) : (
            <div className="grid grid-cols-3 sm:grid-cols-4 gap-2">
              {recentMissing.map((m) => (
                <a
                  key={m.id}
                  href={m.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group block aspect-square rounded-lg overflow-hidden border border-stroke-subtle hover:border-amber-500/50 bg-bg-overlay relative"
                  title={m.filename}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={m.url}
                    alt=""
                    className="w-full h-full object-cover"
                    loading="lazy"
                  />
                  <span className="absolute top-1 right-1 text-[9px] px-1 py-0.5 rounded bg-rose-500/80 text-white opacity-90 group-hover:opacity-100">
                    !
                  </span>
                </a>
              ))}
            </div>
          )}
          <Link
            href="/admin/media?missingAlt=1"
            className="mt-3 inline-flex items-center gap-1 text-xs text-accent-primary hover:underline"
          >
            Mở Media để xử lý hàng loạt <ExternalLink className="h-3 w-3" />
          </Link>
        </section>
      </div>
    </div>
  );
}
