import Link from "next/link";
import type { Prisma, LabelStatus } from "@prisma/client";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { LabelsBulkList } from "./LabelsBulkList";

const STATUSES: LabelStatus[] = ["active", "pending", "rejected", "unverified"];

export default async function AdminLabelsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; q?: string }>;
}) {
  const { status, q } = await searchParams;
  const filterStatus =
    status && STATUSES.includes(status as LabelStatus)
      ? (status as LabelStatus)
      : undefined;

  const session = await auth();
  const viewerRole = (session?.user as { role?: string } | undefined)?.role ?? "member";

  const where: Prisma.LabelWhereInput = {};
  if (filterStatus) where.status = filterStatus;
  if (q?.trim()) {
    const term = q.trim();
    where.OR = [
      { blend: { name: { contains: term, mode: "insensitive" } } },
      { blend: { brand: { name: { contains: term, mode: "insensitive" } } } },
      { uploader: { username: { contains: term, mode: "insensitive" } } },
    ];
  }

  const labels = await db.label.findMany({
    where,
    include: {
      blend: { include: { brand: true } },
      uploader: true,
      versions: { where: { isCurrent: true } },
      cellarChoice: { take: 1 },
    },
    orderBy: { createdAt: "desc" },
    take: 50,
  });

  return (
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        Labels
      </h1>
      <p className="mt-2 text-charcoal/60">
        All uploaded labels. Reject with a reason or delete outright.
      </p>

      <div className="mt-6 flex flex-wrap items-center justify-between gap-4">
        <div className="flex gap-3">
          <Link
            href={`/admin/labels${q ? `?q=${encodeURIComponent(q)}` : ""}`}
            className={`text-sm font-medium ${!filterStatus ? "text-terracotta" : "text-charcoal/60 hover:text-terracotta"}`}
          >
            All
          </Link>
          {STATUSES.map((s) => (
            <Link
              key={s}
              href={`/admin/labels?status=${s}${q ? `&q=${encodeURIComponent(q)}` : ""}`}
              className={`text-sm font-medium ${filterStatus === s ? "text-terracotta" : "text-charcoal/60 hover:text-terracotta"}`}
            >
              {s}
            </Link>
          ))}
        </div>

        <form method="get" className="flex gap-2">
          {filterStatus && <input type="hidden" name="status" value={filterStatus} />}
          <input
            type="text"
            name="q"
            defaultValue={q ?? ""}
            placeholder="Search brand, blend, or uploader"
            className="w-64 rounded border border-charcoal/20 bg-warm-white px-3 py-1.5 text-sm text-charcoal"
          />
          <button
            type="submit"
            className="rounded-full border border-charcoal/20 px-4 py-1.5 text-sm font-medium text-charcoal hover:bg-charcoal/5"
          >
            Search
          </button>
        </form>
      </div>

      {labels.length === 0 ? (
        <p className="mt-8 text-charcoal/60">No labels found.</p>
      ) : (
        <LabelsBulkList
          labels={labels.map((label) => ({
            id: label.id,
            status: label.status,
            rejectionReason: label.rejectionReason,
            brandName: label.blend.brand.name,
            blendName: label.blend.name,
            uploaderUsername: label.uploader.username,
            fileUrl: label.versions[0]?.fileUrl ?? null,
            isCellarChoice: label.cellarChoice.length > 0,
          }))}
          viewerRole={viewerRole}
        />
      )}
    </div>
  );
}
