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

export default async function FeedPage() {
  const session = await auth();
  const userId = (session?.user as { id?: string } | undefined)?.id as string;

  const followedIds = (
    await db.follow.findMany({
      where: { followerId: userId },
      select: { followingId: true },
    })
  ).map((f) => f.followingId);

  const labels =
    followedIds.length === 0
      ? []
      : await db.label.findMany({
          where: { uploaderId: { in: followedIds }, status: "active" },
          orderBy: { createdAt: "desc" },
          take: 60,
          include: {
            blend: { include: { brand: true } },
            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: label.blend.brand.name,
      brandSlug: label.blend.brand.slug,
      blendName: label.blend.name,
      blendSlug: label.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,
    }));

  return (
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        Following Feed
      </h1>
      <p className="mt-2 text-charcoal/60">
        Uploads from people you follow.
      </p>

      {followedIds.length === 0 ? (
        <p className="mt-16 text-center text-charcoal/60">
          You&apos;re not following anyone yet.{" "}
          <Link href="/labels" className="text-terracotta hover:underline">
            Browse the gallery
          </Link>{" "}
          to find people to follow.
        </p>
      ) : cards.length === 0 ? (
        <p className="mt-16 text-center text-charcoal/60">
          No uploads yet from people you follow.
        </p>
      ) : (
        <ul className="mt-10 grid grid-cols-2 gap-8 sm:grid-cols-3">
          {cards.map((card) => (
            <li key={card.id}>
              <LabelCard label={card} />
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
