import Link from "next/link";
import { notFound } from "next/navigation";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { LabelCard, type LabelCardData } from "@/components/labels/LabelCard";
import { getHighestBadgesForUsers } from "@/lib/badges";
import { RequestLabelButton } from "./RequestLabelButton";

export default async function BlendPage({
  params,
}: {
  params: Promise<{ slug: string; blendSlug: string }>;
}) {
  const { slug, blendSlug } = await params;
  const brand = await db.brand.findUnique({ where: { slug } });

  if (!brand) {
    notFound();
  }

  const blend = await db.blend.findUnique({
    where: { brandId_slug: { brandId: brand.id, slug: blendSlug } },
  });

  if (!blend) {
    notFound();
  }

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

  const highestBadges = await getHighestBadgesForUsers(
    Array.from(new Set(labels.map((label) => label.uploaderId))),
  );

  const cards: LabelCardData[] = labels
    .filter((label) => label.versions[0])
    .map((label) => ({
      id: label.id,
      fileUrl: label.versions[0].fileUrl,
      brandName: brand.name,
      brandSlug: brand.slug,
      blendName: blend.name,
      blendSlug: blend.slug,
      uploaderUsername: label.uploader.username,
      uploaderAvatarUrl: label.uploader.avatarUrl,
      uploaderHighestBadgeName: highestBadges.get(label.uploaderId)?.name ?? null,
      thumbsUpCount: label.thumbsUpCount,
      isCellarChoice: label.cellarChoice.length > 0,
      isRequestFulfillment: label.fulfilledRequestId !== null,
    }));

  const session = await auth();
  const viewerId = (session?.user as { id?: string } | undefined)?.id;
  const [existingRequest, requestCount] = await Promise.all([
    viewerId
      ? db.labelRequest.findUnique({
          where: { blendId_requesterId: { blendId: blend.id, requesterId: viewerId } },
        })
      : null,
    db.labelRequest.count({ where: { blendId: blend.id } }),
  ]);

  return (
    <main className="mx-auto max-w-6xl px-6 py-16">
      <Link
        href={`/brands/${brand.slug}`}
        className="text-sm text-terracotta hover:underline"
      >
        &larr; {brand.name}
      </Link>
      <h1 className="mt-4 font-heading text-4xl font-semibold text-terracotta">
        {blend.name}
      </h1>

      {cards.length === 0 ? (
        <div className="mt-8">
          <p className="text-charcoal/60">No labels yet for this blend.</p>
          <div className="mt-4">
            <RequestLabelButton
              blendId={blend.id}
              requestCount={requestCount}
              alreadyRequested={Boolean(existingRequest)}
              isLoggedIn={Boolean(viewerId)}
            />
          </div>
        </div>
      ) : (
        <ul className="mt-10 grid grid-cols-2 gap-8 sm:grid-cols-3 lg:grid-cols-5">
          {cards.map((card) => (
            <li key={card.id}>
              <LabelCard label={card} />
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}
