import Link from "next/link";
import { notFound } from "next/navigation";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { getRejectionMessage } from "@/lib/rejection-message";
import { getSettingNumber } from "@/lib/settings";
import { getHighestBadge } from "@/lib/badges";
import { CellarChoiceBadge } from "@/components/labels/CellarChoiceBadge";
import { ReplaceVersionForm } from "./ReplaceVersionForm";
import { EditBrandBlendForm } from "./EditBrandBlendForm";
import { VoteButtons } from "./VoteButtons";
import { DownloadButton } from "./DownloadButton";
import { FlagButton } from "./FlagButton";
import { UploaderCard } from "./UploaderCard";
import { AddToFolderButton } from "./AddToFolderButton";
import { FixSuggestionButton } from "./FixSuggestionButton";

export default async function LabelDetailPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ v?: string }>;
}) {
  const { id } = await params;
  const { v } = await searchParams;

  const label = await db.label.findUnique({
    where: { id },
    include: {
      blend: { include: { brand: true } },
      uploader: true,
      versions: { orderBy: { versionNumber: "desc" } },
      cellarChoice: { take: 1 },
    },
  });

  if (!label) {
    notFound();
  }

  const minSourceDimension = await getSettingNumber("label_min_dimension", 825);

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

  const requestedVersion = v ? Number(v) : null;
  const displayedVersion =
    label.versions.find((ver) => ver.versionNumber === requestedVersion) ??
    label.versions.find((ver) => ver.isCurrent) ??
    label.versions[0];

  const rejectionMessage = label.rejectionReason
    ? await getRejectionMessage(label.rejectionReason)
    : null;

  const [userVote, highestBadge, followRow, userFolders, savedIn] = await Promise.all([
    viewerId
      ? db.labelVote.findUnique({
          where: { labelId_userId: { labelId: label.id, userId: viewerId } },
        })
      : null,
    getHighestBadge(label.uploaderId),
    viewerId
      ? db.follow.findUnique({
          where: {
            followerId_followingId: {
              followerId: viewerId,
              followingId: label.uploaderId,
            },
          },
        })
      : null,
    viewerId
      ? db.savedFolder.findMany({ where: { userId: viewerId }, orderBy: { name: "asc" } })
      : [],
    viewerId
      ? db.savedLabel.findMany({ where: { userId: viewerId, labelId: label.id } })
      : [],
  ]);

  const savedFolderIds = new Set(savedIn.map((s) => s.folderId).filter(Boolean));
  const isFavorited = savedIn.some((s) => s.folderId === null);

  const fileExtension = displayedVersion?.fileUrl.split(".").pop() ?? "png";
  const downloadFileName = `${label.blend.brand.name}-${label.blend.name}.${fileExtension}`;

  return (
    <div className="mx-auto max-w-2xl px-6 py-16">
      {label.status === "rejected" && (
        <div className="mb-6 rounded bg-terracotta/10 px-4 py-3 text-terracotta">
          <p className="font-medium">This label was rejected.</p>
          <p className="text-sm">
            {rejectionMessage}
            {label.rejectionNote ? ` (${label.rejectionNote})` : ""}
          </p>
        </div>
      )}
      {label.status === "unverified" && (
        <div className="mb-6 rounded bg-gold/10 px-4 py-3 text-sm text-charcoal">
          {isOwner ? (
            "This label is unverified. Waiting for the community to confirm the correct brand and blend."
          ) : viewerId ? (
            <>
              This label is unverified. If you can confirm the brand and
              blend, <FixSuggestionButton labelId={label.id} />.
            </>
          ) : (
            <>
              This label is unverified.{" "}
              <Link href="/login" className="text-terracotta hover:underline">
                Log in
              </Link>{" "}
              to suggest a fix.
            </>
          )}
        </div>
      )}

      {displayedVersion && (
        <div className="flex justify-center">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={displayedVersion.fileUrl}
            alt={`${label.blend.brand.name} ${label.blend.name} label`}
            className="h-72 w-72 rounded-full border border-charcoal/10 object-cover"
          />
        </div>
      )}

      <div className="mt-6 text-center">
        <h1 className="font-heading text-3xl font-semibold text-terracotta">
          <Link href={`/brands/${label.blend.brand.slug}`} className="hover:underline">
            {label.blend.brand.name}
          </Link>
          {" - "}
          <Link
            href={`/brands/${label.blend.brand.slug}/${label.blend.slug}`}
            className="hover:underline"
          >
            {label.blend.name}
          </Link>
        </h1>
        {label.cellarChoice.length > 0 && (
          <div className="mt-2 flex justify-center">
            <CellarChoiceBadge />
          </div>
        )}
        {label.fulfilledRequestId && (
          <p className="mt-2 text-sm text-charcoal/50">
            Created in response to a community request
          </p>
        )}
        {label.versions.length > 1 && displayedVersion && (
          <p className="mt-2 text-charcoal/60">
            Version {displayedVersion.versionNumber} of {label.versions.length}
          </p>
        )}
      </div>

      <div className="mt-6 flex flex-wrap items-center justify-center gap-3">
        <VoteButtons
          labelId={label.id}
          thumbsUpCount={label.thumbsUpCount}
          userVote={userVote?.voteType ?? null}
          isLoggedIn={Boolean(viewerId)}
        />
        {displayedVersion && (
          <DownloadButton
            labelId={label.id}
            fileUrl={displayedVersion.fileUrl}
            fileName={downloadFileName}
          />
        )}
        <Link
          href={viewerId ? `/sheet-builder?label=${label.id}` : "/login"}
          className="rounded-full border border-charcoal/20 px-5 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
        >
          Add to Sheet
        </Link>
        <AddToFolderButton
          labelId={label.id}
          isFavorited={isFavorited}
          folders={userFolders.map((f) => ({
            id: f.id,
            name: f.name,
            isSaved: savedFolderIds.has(f.id),
          }))}
          isLoggedIn={Boolean(viewerId)}
        />
      </div>

      <div className="mt-8">
        <UploaderCard
          uploader={{
            id: label.uploader.id,
            username: label.uploader.username,
            avatarUrl: label.uploader.avatarUrl,
          }}
          highestBadgeName={highestBadge?.name ?? null}
          viewer={{
            id: viewerId ?? null,
            isFollowing: Boolean(followRow),
            isWatching: Boolean(followRow?.watchUploads),
          }}
        />
      </div>

      <div className="mt-6 flex justify-center">
        <FlagButton labelId={label.id} isLoggedIn={Boolean(viewerId)} />
      </div>

      {isOwner && (
        <div className="mt-10 flex flex-col gap-8 border-t border-charcoal/10 pt-8">
          <div>
            <h2 className="font-heading text-xl font-semibold text-charcoal">
              Replace image
            </h2>
            <p className="mt-1 text-sm text-charcoal/60">
              Uploading a new image adds a new version. Older versions stay
              visible in the history.
            </p>
            <div className="mt-4">
              <ReplaceVersionForm
                labelId={label.id}
                minSourceDimension={minSourceDimension}
              />
            </div>
          </div>

          <div>
            <h2 className="font-heading text-xl font-semibold text-charcoal">
              Edit brand/blend
            </h2>
            <div className="mt-4">
              <EditBrandBlendForm labelId={label.id} />
            </div>
          </div>
        </div>
      )}

      {label.versions.length > 1 && (
        <div className="mt-10 border-t border-charcoal/10 pt-8">
          <h2 className="font-heading text-xl font-semibold text-charcoal">
            Version history
          </h2>
          <ul className="mt-4 flex flex-wrap gap-4">
            {label.versions.map((version) => (
              <li key={version.id}>
                <Link
                  href={`/labels/${label.id}?v=${version.versionNumber}`}
                  className={`flex flex-col items-center gap-1 rounded-lg border p-2 text-xs ${
                    version.id === displayedVersion?.id
                      ? "border-terracotta"
                      : "border-charcoal/10 hover:border-charcoal/30"
                  }`}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={version.fileUrl}
                    alt={`Version ${version.versionNumber}`}
                    className="h-20 w-20 rounded-full border border-charcoal/10 object-cover"
                  />
                  <span className="font-medium text-charcoal">
                    v{version.versionNumber}
                    {version.isCurrent && " (current)"}
                  </span>
                  <span className="text-charcoal/50">
                    {version.width}x{version.height}px
                  </span>
                </Link>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
