import { Search, Crown, ShieldOff, ShieldCheck } from "lucide-react";
import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { requireAdmin, audit } from "@/lib/admin-guard";
import { BulkUserActions } from "@/components/admin/bulk-user-actions";

export const dynamic = "force-dynamic";

const PAGE_SIZE = 25;

type Props = { searchParams: Promise<{ q?: string; page?: string; role?: string }> };

async function setRoleAction(formData: FormData) {
  "use server";
  const admin = await requireAdmin();
  const userId = String(formData.get("userId") ?? "");
  const newRole = String(formData.get("role") ?? "USER");
  if (!userId || !["USER", "ADMIN"].includes(newRole)) return;
  if (userId === admin.userId && newRole !== "ADMIN") {
    // Don't let an admin demote themselves — easy way to lock yourself out.
    return;
  }
  const before = await prisma.user.findUnique({
    where: { id: userId },
    select: { role: true, email: true },
  });
  await prisma.user.update({ where: { id: userId }, data: { role: newRole } });
  await audit({
    actorId: admin.userId,
    actorName: admin.name,
    action: "user.role_change",
    target: userId,
    metadata: { from: before?.role ?? null, to: newRole, email: before?.email },
  });
  revalidatePath("/admin/users");
}

async function setPlanAction(formData: FormData) {
  "use server";
  const admin = await requireAdmin();
  const userId = String(formData.get("userId") ?? "");
  const newPlan = String(formData.get("plan") ?? "FREE");
  if (!userId || !["FREE", "PREMIUM"].includes(newPlan)) return;
  await prisma.user.update({ where: { id: userId }, data: { plan: newPlan } });
  await audit({
    actorId: admin.userId,
    actorName: admin.name,
    action: "user.plan_change",
    target: userId,
    metadata: { to: newPlan },
  });
  revalidatePath("/admin/users");
}

export default async function AdminUsers({ searchParams }: Props) {
  await requireAdmin();
  const sp = await searchParams;
  const q = (sp.q ?? "").trim();
  const page = Math.max(1, parseInt(sp.page ?? "1", 10) || 1);
  const roleFilter = sp.role ?? "";

  const filter = {
    ...(q
      ? {
          OR: [
            { email: { contains: q, mode: "insensitive" as const } },
            { name: { contains: q, mode: "insensitive" as const } },
          ],
        }
      : {}),
    ...(roleFilter ? { role: roleFilter } : {}),
  };

  const [users, total] = await Promise.all([
    prisma.user.findMany({
      where: filter,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        plan: true,
        emailVerified: true,
        createdAt: true,
        _count: { select: { charts: true, conversations: true } },
      },
    }),
    prisma.user.count({ where: filter }),
  ]);

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

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-ink-primary text-2xl font-semibold lg:text-3xl">
          Người dùng
        </h1>
        <p className="text-ink-secondary mt-1 text-sm">
          {total} user — phân trang {PAGE_SIZE}/page.
        </p>
      </div>

      <form
        method="GET"
        className="border-stroke-subtle bg-bg-elevated/40 mb-4 flex flex-wrap items-end gap-3 rounded-xl border p-4"
      >
        <div className="min-w-[200px] flex-1">
          <label className="text-ink-muted block text-xs">Tìm theo email/tên</label>
          <div className="relative mt-1">
            <Search className="text-ink-muted absolute top-1/2 left-2.5 h-4 w-4 -translate-y-1/2" />
            <input
              name="q"
              defaultValue={q}
              placeholder="user@example.com"
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border py-2 pr-3 pl-9 text-sm focus:outline-none"
            />
          </div>
        </div>
        <div>
          <label className="text-ink-muted block text-xs">Role</label>
          <select
            name="role"
            defaultValue={roleFilter}
            className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold mt-1 rounded-md border px-3 py-2 text-sm focus:outline-none"
          >
            <option value="">Tất cả</option>
            <option value="USER">USER</option>
            <option value="ADMIN">ADMIN</option>
          </select>
        </div>
        <button
          type="submit"
          className="bg-brand-gold text-bg-base rounded-md px-4 py-2 text-sm font-medium"
        >
          Lọc
        </button>
      </form>

      <BulkUserActions />

      <div className="border-stroke-subtle bg-bg-elevated/40 overflow-x-auto rounded-xl border">
        <table className="w-full text-sm">
          <thead className="border-stroke-subtle bg-bg-overlay/40 border-b">
            <tr className="text-ink-muted text-left text-[11px] tracking-wider uppercase">
              <th className="w-10 px-4 py-3">
                <input
                  type="checkbox"
                  id="user-select-all"
                  className="bg-bg-inset border-stroke-default cursor-pointer rounded border"
                  aria-label="Chọn toàn bộ"
                />
              </th>
              <th className="px-4 py-3">User</th>
              <th className="px-4 py-3">Role</th>
              <th className="px-4 py-3">Plan</th>
              <th className="px-4 py-3 text-right">Lá số / Chat</th>
              <th className="px-4 py-3">Ngày đăng ký</th>
            </tr>
          </thead>
          <tbody className="divide-stroke-subtle/50 divide-y">
            {users.map((u) => (
              <tr key={u.id} className="hover:bg-bg-overlay/30">
                <td className="px-4 py-3">
                  <input
                    type="checkbox"
                    data-user-id={u.id}
                    className="bg-bg-inset border-stroke-default cursor-pointer rounded border"
                    aria-label={`Chọn ${u.email}`}
                  />
                </td>
                <td className="px-4 py-3">
                  <div className="text-ink-primary font-medium">{u.name}</div>
                  <div className="text-ink-muted text-xs">
                    {u.email}{" "}
                    {u.emailVerified ? (
                      <ShieldCheck
                        className="text-brand-gold/70 ml-1 inline h-3 w-3"
                        aria-label="Email verified"
                      />
                    ) : (
                      <ShieldOff
                        className="text-ink-muted/60 ml-1 inline h-3 w-3"
                        aria-label="Not verified"
                      />
                    )}
                  </div>
                </td>
                <td className="px-4 py-3">
                  <form action={setRoleAction} className="inline-flex items-center gap-1">
                    <input type="hidden" name="userId" value={u.id} />
                    <select
                      name="role"
                      defaultValue={u.role ?? "USER"}
                      className="bg-bg-inset border-stroke-default rounded border px-2 py-1 text-xs"
                    >
                      <option value="USER">USER</option>
                      <option value="ADMIN">ADMIN</option>
                    </select>
                    <button
                      type="submit"
                      className="text-brand-gold hover:text-brand-gold-soft text-xs"
                    >
                      Lưu
                    </button>
                  </form>
                  {u.role === "ADMIN" ? (
                    <Crown className="text-brand-gold mt-1 inline h-3 w-3" />
                  ) : null}
                </td>
                <td className="px-4 py-3">
                  <form action={setPlanAction} className="inline-flex items-center gap-1">
                    <input type="hidden" name="userId" value={u.id} />
                    <select
                      name="plan"
                      defaultValue={u.plan ?? "FREE"}
                      className="bg-bg-inset border-stroke-default rounded border px-2 py-1 text-xs"
                    >
                      <option value="FREE">FREE</option>
                      <option value="PREMIUM">PREMIUM</option>
                    </select>
                    <button
                      type="submit"
                      className="text-brand-gold hover:text-brand-gold-soft text-xs"
                    >
                      Lưu
                    </button>
                  </form>
                </td>
                <td className="px-4 py-3 text-right">
                  <span className="text-ink-secondary text-xs">
                    {u._count.charts} / {u._count.conversations}
                  </span>
                </td>
                <td className="text-ink-muted px-4 py-3 text-xs">
                  {u.createdAt.toLocaleDateString("vi-VN")}
                </td>
              </tr>
            ))}
            {users.length === 0 ? (
              <tr>
                <td colSpan={6} className="text-ink-muted px-4 py-8 text-center text-sm">
                  Không có user nào khớp bộ lọc.
                </td>
              </tr>
            ) : null}
          </tbody>
        </table>
      </div>

      {totalPages > 1 ? (
        <div className="mt-4 flex items-center justify-between text-xs">
          <span className="text-ink-muted">
            Trang {page}/{totalPages}
          </span>
          <div className="flex gap-2">
            {page > 1 ? (
              <a
                href={`/admin/users?q=${encodeURIComponent(q)}&role=${roleFilter}&page=${page - 1}`}
                className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 rounded-md border px-3 py-1.5"
              >
                ← Trước
              </a>
            ) : null}
            {page < totalPages ? (
              <a
                href={`/admin/users?q=${encodeURIComponent(q)}&role=${roleFilter}&page=${page + 1}`}
                className="border-stroke-default text-ink-secondary hover:border-brand-gold/50 rounded-md border px-3 py-1.5"
              >
                Sau →
              </a>
            ) : null}
          </div>
        </div>
      ) : null}
    </div>
  );
}
