import Link from "next/link";
import { prisma } from "@/lib/db";
import { ExternalLink, RefreshCw } from "lucide-react";
import { PingButton } from "./_ping-button";

export const dynamic = "force-dynamic";

const SITE = process.env.NEXT_PUBLIC_SITE_URL ?? "https://v2.finzone.io.vn";

export default async function SitemapAdminPage() {
  const [articleCount, categoryCount, totalIndexable, excludedCount, recentArticles] =
    await Promise.all([
      prisma.article.count({ where: { status: "published", noIndex: false } }),
      prisma.category.count(),
      prisma.article.count({ where: { status: "published" } }),
      prisma.article.count({ where: { status: "published", noIndex: true } }),
      prisma.article.findMany({
        where: { status: "published" },
        orderBy: { publishedAt: "desc" },
        take: 10,
        select: {
          id: true,
          slug: true,
          title: true,
          publishedAt: true,
          updatedAt: true,
          noIndex: true,
        },
      }),
    ]);

  const stats = [
    { label: "URL trong sitemap", value: articleCount + categoryCount + 2, tone: "text-emerald-300" },
    { label: "Bài index được", value: articleCount, tone: "text-emerald-300/80" },
    {
      label: "Bài noIndex",
      value: excludedCount,
      tone: excludedCount > 0 ? "text-amber-300" : "text-ink-secondary",
    },
    { label: "Chuyên mục", value: categoryCount, tone: "text-ink-secondary" },
  ];

  return (
    <div>
      <div className="mb-6">
        <h2 className="font-display font-semibold text-lg mb-1">Sitemap & Search Engine Ping</h2>
        <p className="text-sm text-ink-muted">
          Sitemap được sinh động từ DB. Bài có <code className="text-xs">noIndex</code>{" "}
          tự động bị loại khỏi sitemap.
        </p>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
        {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>
          </div>
        ))}
      </div>

      <div className="grid lg:grid-cols-2 gap-4 mb-6">
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4">
          <h3 className="font-medium mb-2 flex items-center gap-2">
            <RefreshCw className="h-4 w-4 text-accent-primary" />
            Sitemap URLs
          </h3>
          <ul className="space-y-1.5 text-sm">
            <li>
              <a
                href={`${SITE}/sitemap.xml`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-accent-primary hover:underline flex items-center gap-1.5 font-mono text-xs"
              >
                {SITE}/sitemap.xml <ExternalLink className="h-3 w-3" />
              </a>
            </li>
            <li>
              <a
                href={`${SITE}/robots.txt`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-accent-primary hover:underline flex items-center gap-1.5 font-mono text-xs"
              >
                {SITE}/robots.txt <ExternalLink className="h-3 w-3" />
              </a>
            </li>
            <li>
              <a
                href={`${SITE}/feed.xml`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-accent-primary hover:underline flex items-center gap-1.5 font-mono text-xs"
              >
                {SITE}/feed.xml <ExternalLink className="h-3 w-3" />
              </a>
            </li>
          </ul>
          <p className="text-[11px] text-ink-muted mt-3">
            Sitemap revalidate sau 600s. Bài mới publish sẽ xuất hiện trong vòng 10 phút.
          </p>
        </div>

        <PingButton />
      </div>

      <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">
          <h3 className="font-medium">10 bài mới nhất trong sitemap</h3>
        </div>
        <table className="w-full text-sm">
          <thead className="text-xs text-ink-muted bg-bg-elevated/40">
            <tr>
              <th className="px-4 py-2 text-left font-normal">Tiêu đề</th>
              <th className="px-4 py-2 text-left font-normal">Slug</th>
              <th className="px-4 py-2 text-left font-normal">Cập nhật</th>
              <th className="px-4 py-2 text-left font-normal">Status</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-stroke-subtle/40">
            {recentArticles.map((a) => (
              <tr key={a.id} className="hover:bg-bg-overlay/40">
                <td className="px-4 py-2.5">
                  <Link
                    href={`/admin/articles/${a.id}`}
                    className="hover:text-accent-primary line-clamp-1"
                  >
                    {a.title}
                  </Link>
                </td>
                <td className="px-4 py-2.5 text-ink-muted font-mono text-xs">/{a.slug}</td>
                <td className="px-4 py-2.5 text-ink-muted text-xs">
                  {a.updatedAt.toLocaleDateString("vi-VN")}
                </td>
                <td className="px-4 py-2.5">
                  {a.noIndex ? (
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-300">
                      noIndex
                    </span>
                  ) : (
                    <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-300">
                      indexable
                    </span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="px-4 py-3 border-t border-stroke-subtle bg-bg-elevated/40 text-xs text-ink-muted">
          {totalIndexable} bài tổng — chỉ hiển thị 10 mới nhất.
        </div>
      </section>
    </div>
  );
}
