import Link from "next/link";
import { prisma } from "@/lib/db";
import { resolveAction, deleteAction, autoCreateRedirectAction } from "./_actions";
import { Buttons } from "./_form";

export const dynamic = "force-dynamic";

const PAGE_SIZE = 50;

function fmtDate(d: Date): string {
  return new Intl.DateTimeFormat("vi-VN", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(d);
}

export default async function NotFoundMonitorPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; page?: string }>;
}) {
  const sp = await searchParams;
  const showResolved = sp.status === "resolved";
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);

  const where = { resolved: showResolved };

  const [logs, total, totalUnresolved, totalResolved] = await Promise.all([
    prisma.notFoundLog.findMany({
      where,
      orderBy: [{ hits: "desc" }, { lastSeen: "desc" }],
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.notFoundLog.count({ where }),
    prisma.notFoundLog.count({ where: { resolved: false } }),
    prisma.notFoundLog.count({ where: { resolved: true } }),
  ]);

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">404 Monitor</h1>
        <p className="text-sm text-ink-muted">
          Theo dõi đường dẫn bị 404 trên site, xếp theo số lần truy cập. Tạo redirect để cứu traffic.
        </p>
      </div>

      <div className="flex gap-2 mb-5">
        <Link
          href="/admin/super-seo/404-monitor"
          className={`px-3 py-1.5 rounded-lg text-sm border ${
            !showResolved
              ? "bg-accent-primary/15 border-accent-primary/40 text-accent-primary"
              : "bg-bg-elevated border-stroke-subtle text-ink-secondary hover:border-accent-primary/40"
          }`}
        >
          Chưa xử lý ({totalUnresolved})
        </Link>
        <Link
          href="/admin/super-seo/404-monitor?status=resolved"
          className={`px-3 py-1.5 rounded-lg text-sm border ${
            showResolved
              ? "bg-emerald-500/15 border-emerald-500/40 text-emerald-300"
              : "bg-bg-elevated border-stroke-subtle text-ink-secondary hover:border-accent-primary/40"
          }`}
        >
          Đã xử lý ({totalResolved})
        </Link>
      </div>

      {logs.length === 0 ? (
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-10 text-center">
          <div className="text-3xl mb-2">{showResolved ? "📁" : "🎉"}</div>
          <p className="text-sm text-ink-muted">
            {showResolved ? "Chưa có 404 nào được đánh dấu xử lý." : "Tuyệt vời — chưa có 404 nào!"}
          </p>
        </div>
      ) : (
        <div className="rounded-xl border border-stroke-subtle overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-bg-elevated/60 text-left">
              <tr className="border-b border-stroke-subtle">
                <th className="px-4 py-2.5 font-medium text-ink-muted">Path</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted text-center">Hits</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Lần cuối</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Referer</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted text-right">Hành động</th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr
                  key={log.id}
                  className="border-b border-stroke-subtle/60 last:border-0 hover:bg-bg-elevated/30 transition"
                >
                  <td className="px-4 py-3 font-mono text-xs">
                    <a
                      href={log.path}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-ink-primary hover:text-accent-primary break-all"
                    >
                      {log.path}
                    </a>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span
                      className={`text-xs font-medium ${
                        log.hits >= 10 ? "text-rose-300" : log.hits >= 3 ? "text-amber-300" : "text-ink-muted"
                      }`}
                    >
                      {log.hits}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-ink-muted">{fmtDate(log.lastSeen)}</td>
                  <td className="px-4 py-3 text-xs text-ink-muted truncate max-w-[260px]">
                    {log.lastReferrer ? (
                      <a
                        href={log.lastReferrer}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="hover:text-accent-primary truncate block"
                      >
                        {log.lastReferrer.replace(/^https?:\/\//, "")}
                      </a>
                    ) : (
                      "—"
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <Buttons
                      id={log.id}
                      path={log.path}
                      resolved={log.resolved}
                      autoCreate={autoCreateRedirectAction}
                      resolve={resolveAction}
                      del={deleteAction}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-5">
          <Link
            href={
              page > 1
                ? `/admin/super-seo/404-monitor?${showResolved ? "status=resolved&" : ""}page=${page - 1}`
                : "#"
            }
            className={`px-4 py-2 rounded-lg text-sm border border-stroke-subtle hover:border-accent-primary transition ${
              page <= 1 ? "pointer-events-none opacity-40" : ""
            }`}
          >
            ← Trước
          </Link>
          <span className="text-xs text-ink-muted">
            {page} / {totalPages}
          </span>
          <Link
            href={
              page < totalPages
                ? `/admin/super-seo/404-monitor?${showResolved ? "status=resolved&" : ""}page=${page + 1}`
                : "#"
            }
            className={`px-4 py-2 rounded-lg text-sm border border-stroke-subtle hover:border-accent-primary transition ${
              page >= totalPages ? "pointer-events-none opacity-40" : ""
            }`}
          >
            Sau →
          </Link>
        </div>
      )}
    </div>
  );
}
