import Link from "next/link";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { RequestMeta } from "./RequestMeta";
import { AlphabetFilter } from "./AlphabetFilter";
import { NewRequestToggle } from "./NewRequestToggle";

export default async function RequestsPage({
  searchParams,
}: {
  searchParams: Promise<{ letter?: string; sort?: string }>;
}) {
  const { letter: rawLetter, sort: rawSort } = await searchParams;
  const activeLetter =
    rawLetter && /^[A-Za-z]$/.test(rawLetter) ? rawLetter.toUpperCase() : null;
  const sort = rawSort === "alphabetical" ? "alphabetical" : "most_requested";

  const session = await auth();
  const viewerId = (session?.user as { id?: string } | undefined)?.id;

  const grouped = await db.labelRequest.groupBy({
    by: ["blendId"],
    _count: { blendId: true },
  });

  if (grouped.length === 0) {
    return (
      <div className="mx-auto max-w-3xl px-6 py-16">
        <h1 className="font-heading text-4xl font-semibold text-terracotta">
          Label Requests
        </h1>
        <p className="mt-8 text-charcoal/60">
          No open requests yet. Visit a blend page with no labels to request
          one.
        </p>
      </div>
    );
  }

  const blendIds = grouped.map((g) => g.blendId);
  const blends = await db.blend.findMany({
    where: { id: { in: blendIds } },
    include: {
      brand: true,
      _count: { select: { labels: { where: { status: "active" } } } },
    },
  });
  const blendMap = new Map(blends.map((b) => [b.id, b]));

  const [viewer, viewerRequests] = await Promise.all([
    viewerId ? db.user.findUnique({ where: { id: viewerId } }) : null,
    viewerId
      ? db.labelRequest.findMany({
          where: { requesterId: viewerId, blendId: { in: blendIds } },
          select: { blendId: true },
        })
      : [],
  ]);
  const requestedByViewer = new Set(viewerRequests.map((r) => r.blendId));
  const isContributor = viewer?.contributorFlag ?? false;

  let rows = grouped
    .map((group) => ({
      blend: blendMap.get(group.blendId),
      count: group._count.blendId,
    }))
    .filter((row): row is { blend: NonNullable<typeof row.blend>; count: number } =>
      Boolean(row.blend),
    );

  const availableLetters = new Set(
    rows.map((row) => row.blend.brand.name.charAt(0).toUpperCase()),
  );

  if (activeLetter) {
    rows = rows.filter(
      (row) => row.blend.brand.name.charAt(0).toUpperCase() === activeLetter,
    );
  }

  rows =
    sort === "alphabetical"
      ? rows.sort((a, b) =>
          `${a.blend.brand.name} ${a.blend.name}`.localeCompare(
            `${b.blend.brand.name} ${b.blend.name}`,
          ),
        )
      : rows.sort((a, b) => b.count - a.count);

  const currentParams = { letter: rawLetter, sort: rawSort };

  return (
    <div className="mx-auto max-w-3xl px-6 py-16">
      <h1 className="font-heading text-4xl font-semibold text-terracotta">
        Label Requests
      </h1>
      <p className="mt-2 text-charcoal/60">
        Blends the community wants labels for.
      </p>

      {isContributor && (
        <div className="mt-4">
          <NewRequestToggle initialEnabled={viewer?.notifyNewRequests ?? false} />
        </div>
      )}

      <div className="mt-6">
        <AlphabetFilter
          activeLetter={activeLetter}
          availableLetters={availableLetters}
          current={currentParams}
        />
      </div>

      <div className="mt-4 flex items-center gap-4 text-sm">
        <span className="text-charcoal/60">Sort:</span>
        <Link
          href={{
            pathname: "/requests",
            query: { ...(activeLetter ? { letter: activeLetter } : {}) },
          }}
          className={`font-medium ${
            sort === "most_requested"
              ? "text-terracotta"
              : "text-charcoal/60 hover:text-terracotta"
          }`}
        >
          Most requested
        </Link>
        <Link
          href={{
            pathname: "/requests",
            query: {
              sort: "alphabetical",
              ...(activeLetter ? { letter: activeLetter } : {}),
            },
          }}
          className={`font-medium ${
            sort === "alphabetical"
              ? "text-terracotta"
              : "text-charcoal/60 hover:text-terracotta"
          }`}
        >
          Brand A-Z
        </Link>
      </div>

      {rows.length === 0 ? (
        <p className="mt-10 text-charcoal/60">
          No requested blends start with &ldquo;{activeLetter}&rdquo;.
        </p>
      ) : (
        <ul className="mt-6 flex flex-col divide-y divide-charcoal/10 border-t border-charcoal/10">
          {rows.map(({ blend, count }) => (
            <li key={blend.id} className="flex items-center justify-between py-4">
              <div>
                <Link
                  href={`/brands/${blend.brand.slug}/${blend.slug}`}
                  className="font-medium text-charcoal hover:text-terracotta hover:underline"
                >
                  {blend.brand.name} - {blend.name}
                </Link>
                <RequestMeta
                  blendId={blend.id}
                  initialCount={count}
                  labelCount={blend._count.labels}
                  initialAlreadyRequested={requestedByViewer.has(blend.id)}
                  isLoggedIn={Boolean(viewerId)}
                />
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
