import Link from "next/link";
import { FileText, Plus, Pencil, Eye, EyeOff, Trash2 } from "lucide-react";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { categoryLabel, statusOf, BLOG_CATEGORIES } from "@/lib/blog";
import { togglePublishFormAction, deleteBlogPostFormAction } from "./_actions";

export const dynamic = "force-dynamic";

type SearchParams = Promise<{ q?: string; cat?: string; status?: string }>;

export default async function AdminBlogList({ searchParams }: { searchParams: SearchParams }) {
  await requireAdmin();
  const sp = await searchParams;
  const q = (sp.q ?? "").trim();
  const cat = (sp.cat ?? "").trim();
  const status = (sp.status ?? "").trim(); // "published" | "draft" | ""

  const where: Record<string, unknown> = {};
  if (q) {
    where.OR = [
      { title: { contains: q, mode: "insensitive" } },
      { slug: { contains: q, mode: "insensitive" } },
    ];
  }
  if (cat) where.category = cat;
  if (status === "published") where.publishedAt = { not: null };
  else if (status === "draft") where.publishedAt = null;

  const posts = await prisma.blogPost.findMany({
    where,
    orderBy: { updatedAt: "desc" },
    take: 100,
  });

  const totals = await prisma.blogPost.groupBy({
    by: ["category"],
    _count: true,
  });

  return (
    <div>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <div className="text-ink-muted text-[11px] tracking-[0.2em] uppercase">Quản trị</div>
          <h1 className="font-display text-ink-primary mt-1 flex items-center gap-2 text-2xl font-semibold">
            <FileText className="text-brand-gold/70 h-5 w-5" />
            Blog
          </h1>
          <div className="text-ink-muted mt-1 text-sm">
            {posts.length} bài hiển thị · tổng{" "}
            {totals.reduce((s, t) => s + (t._count as number), 0)} bài
          </div>
        </div>
        <Link
          href="/admin/blog/new"
          className="bg-brand-gold/90 hover:bg-brand-gold text-bg-base inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition"
        >
          <Plus className="h-4 w-4" /> Bài mới
        </Link>
      </div>

      {/* Filters */}
      <form
        method="get"
        className="border-stroke-subtle bg-bg-elevated/40 mb-4 flex flex-wrap gap-3 rounded-lg border p-3"
      >
        <input
          type="search"
          name="q"
          defaultValue={q}
          placeholder="Tìm theo tiêu đề / slug…"
          className="border-stroke-subtle bg-bg-base text-ink-primary placeholder:text-ink-muted/60 min-w-[200px] flex-1 rounded-md border px-3 py-1.5 text-sm"
        />
        <select
          name="cat"
          defaultValue={cat}
          className="border-stroke-subtle bg-bg-base text-ink-primary rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">Tất cả chuyên mục</option>
          {BLOG_CATEGORIES.map((c) => (
            <option key={c.key} value={c.key}>
              {c.label}
            </option>
          ))}
        </select>
        <select
          name="status"
          defaultValue={status}
          className="border-stroke-subtle bg-bg-base text-ink-primary rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">Tất cả trạng thái</option>
          <option value="published">Đã xuất bản</option>
          <option value="draft">Bản nháp</option>
        </select>
        <button
          type="submit"
          className="border-stroke-subtle hover:border-brand-gold/40 hover:text-brand-gold text-ink-secondary rounded-md border px-4 py-1.5 text-sm transition"
        >
          Lọc
        </button>
      </form>

      {/* Table */}
      <div className="border-stroke-subtle bg-bg-elevated/40 overflow-hidden rounded-xl border">
        {posts.length === 0 ? (
          <div className="text-ink-muted px-6 py-16 text-center text-sm">
            Chưa có bài nào{q || cat || status ? " khớp bộ lọc" : ""}.{" "}
            <Link href="/admin/blog/new" className="text-brand-gold hover:underline">
              Tạo bài đầu tiên →
            </Link>
          </div>
        ) : (
          <table className="w-full text-sm">
            <thead className="border-stroke-subtle text-ink-muted border-b text-[11px] tracking-[0.15em] uppercase">
              <tr>
                <th className="px-4 py-3 text-left">Tiêu đề</th>
                <th className="px-3 py-3 text-left">Chuyên mục</th>
                <th className="px-3 py-3 text-left">Trạng thái</th>
                <th className="px-3 py-3 text-right">Lượt xem</th>
                <th className="px-3 py-3 text-left">Cập nhật</th>
                <th className="px-3 py-3 text-right">Hành động</th>
              </tr>
            </thead>
            <tbody className="divide-stroke-subtle/60 divide-y">
              {posts.map((p) => {
                const st = statusOf(p.publishedAt);
                return (
                  <tr key={p.id} className="hover:bg-bg-overlay/30 transition">
                    <td className="px-4 py-3">
                      <Link
                        href={`/admin/blog/${p.id}/edit`}
                        className="text-ink-primary hover:text-brand-gold font-medium"
                      >
                        {p.title}
                      </Link>
                      <div className="text-ink-muted mt-0.5 truncate text-xs">/{p.slug}</div>
                    </td>
                    <td className="px-3 py-3">
                      <span className="border-stroke-subtle text-ink-secondary inline-block rounded border px-2 py-0.5 text-xs">
                        {categoryLabel(p.category)}
                      </span>
                    </td>
                    <td className="px-3 py-3">
                      {st === "published" ? (
                        <span className="text-brand-green inline-flex items-center gap-1 text-xs">
                          <span className="bg-brand-green inline-block h-1.5 w-1.5 rounded-full" />
                          Đã xuất bản
                        </span>
                      ) : (
                        <span className="text-ink-muted inline-flex items-center gap-1 text-xs">
                          <span className="bg-ink-muted inline-block h-1.5 w-1.5 rounded-full" />
                          Nháp
                        </span>
                      )}
                    </td>
                    <td className="text-ink-secondary px-3 py-3 text-right tabular-nums">
                      {p.views}
                    </td>
                    <td className="text-ink-muted px-3 py-3 text-xs">
                      {p.updatedAt.toLocaleDateString("vi-VN", {
                        day: "2-digit",
                        month: "2-digit",
                        year: "numeric",
                      })}
                    </td>
                    <td className="px-3 py-3">
                      <div className="flex justify-end gap-1">
                        <Link
                          href={`/admin/blog/${p.id}/edit`}
                          className="hover:bg-bg-overlay text-ink-muted hover:text-brand-gold rounded p-1.5 transition"
                          title="Chỉnh sửa"
                        >
                          <Pencil className="h-3.5 w-3.5" />
                        </Link>
                        <form action={togglePublishFormAction}>
                          <input type="hidden" name="id" value={p.id} />
                          <button
                            type="submit"
                            className="hover:bg-bg-overlay text-ink-muted hover:text-brand-gold rounded p-1.5 transition"
                            title={st === "published" ? "Gỡ xuất bản" : "Xuất bản"}
                          >
                            {st === "published" ? (
                              <EyeOff className="h-3.5 w-3.5" />
                            ) : (
                              <Eye className="h-3.5 w-3.5" />
                            )}
                          </button>
                        </form>
                        <form
                          action={deleteBlogPostFormAction}
                          // Confirm via hidden client confirm — server still validates admin
                        >
                          <input type="hidden" name="id" value={p.id} />
                          <button
                            type="submit"
                            className="hover:bg-bg-overlay text-ink-muted hover:text-brand-red rounded p-1.5 transition"
                            title="Xóa"
                          >
                            <Trash2 className="h-3.5 w-3.5" />
                          </button>
                        </form>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
