import { getTranslations, setRequestLocale } from "next-intl/server";
import { redirect, notFound } from "next/navigation";
import { connectDB } from "@/lib/db";
import { ClientPhotoFolder } from "@/models/ClientPhotoFolder";
import { PhotoRating } from "@/models/PhotoRating";
import { PhotoMetadata } from "@/models/PhotoMetadata";
import { Order } from "@/models/Order";
import { getSessionClientId } from "@/lib/auth";
import { listFolderImages } from "@/lib/nextcloud";
import { ensurePhotoDimensions, computePrintFormatLabel } from "@/lib/photoFormat";
import { needsPhotoWatermark } from "@/lib/watermark";
import { PhotoGalleryClient } from "@/components/orders/PhotoGalleryClient";
import { ShareFolderPanel } from "@/components/account/ShareFolderPanel";
import { Link } from "@/i18n/navigation";
import { getSiteUrl } from "@/lib/seo";
import { formatDateLocale } from "@/lib/orderConstants";
import { AccountPageHeader } from "@/components/account/AccountPageHeader";

export const dynamic = "force-dynamic";

export default async function PhotoFolderPage({
  params,
}: {
  params: Promise<{ locale: string; folderId: string }>;
}) {
  const { locale, folderId } = await params;
  setRequestLocale(locale);
  const t = await getTranslations({ locale, namespace: "photos" });

  const clientId = await getSessionClientId();
  if (!clientId) redirect(`/${locale}/login`);

  await connectDB();
  const folder = await ClientPhotoFolder.findById(folderId).lean();
  if (!folder || String(folder.clientId) !== clientId || !folder.released) notFound();

  const [images, ratings, metadataDocs] = await Promise.all([
    listFolderImages(folder.nextcloudPath).catch(() => []),
    PhotoRating.find({ folderId }).lean(),
    PhotoMetadata.find({ folderId }).lean(),
  ]);
  const ratingByFile = new Map(ratings.map((r) => [r.fileName, r]));
  const metaByFile = new Map(metadataDocs.map((m) => [m.fileName, m]));

  const linkedOrder = folder.orderId ? await Order.findById(folder.orderId).select("paid compensationType").lean() : null;
  const isWatermarked = needsPhotoWatermark(linkedOrder);

  // Noch nicht freigegebene Fotos werden dem Kunden gar nicht erst
  // angezeigt — nicht nur der Download, auch das Vorschaubild bleibt bis zur
  // Freigabe verborgen.
  const approvedFiles = images.filter((fileName) => ratingByFile.get(fileName)?.approvedForDownload);
  // Pixelmaße nur für die tatsächlich sichtbaren (freigegebenen) Fotos
  // nachziehen — für den Rest lohnt sich die Nextcloud-Anfrage nicht, solange
  // sie dem Kunden ohnehin nicht angezeigt werden.
  const dimsByFile = new Map(
    await Promise.all(
      approvedFiles.map(async (fileName) => {
        const existing = metaByFile.get(fileName);
        const dims = await ensurePhotoDimensions(
          clientId,
          folderId,
          fileName,
          folder.nextcloudPath,
          existing ? { widthPx: existing.widthPx, heightPx: existing.heightPx } : undefined
        );
        return [fileName, dims] as const;
      })
    )
  );
  const photos = approvedFiles.map((fileName) => {
    const dims = dimsByFile.get(fileName);
    return {
      fileName,
      stars: ratingByFile.get(fileName)?.stars ?? 0,
      note: ratingByFile.get(fileName)?.note ?? "",
      collection: ratingByFile.get(fileName)?.collection ?? "",
      tags: metaByFile.get(fileName)?.tags ?? [],
      formatLabel: dims?.widthPx != null && dims?.heightPx != null ? computePrintFormatLabel(dims.widthPx, dims.heightPx) : null,
    };
  });

  return (
    <div className="relative">
      <div
        aria-hidden="true"
        className="fixed inset-0 -z-10 pointer-events-none"
        style={{
          background:
            "radial-gradient(ellipse 55% 45% at 88% 15%, rgba(201,138,75,0.08), transparent 62%)," +
            "radial-gradient(ellipse 50% 42% at 8% 85%, rgba(201,138,75,0.06), transparent 65%)",
        }}
      />
      <div>
        <Link href="/account/photos" className="text-xs text-[var(--rk-ink-muted)] transition-colors hover:text-[var(--rk-ink)]">
          ← {t("title")}
        </Link>
        <div className="mt-6">
          <AccountPageHeader eyebrow={t("eyebrow")} title={folder.label || folder.nextcloudPath} />
          <p className="-mt-4 text-sm text-[var(--rk-ink-muted)]">
            {formatDateLocale(new Date(folder.assignedAt), locale)}
            {photos.length > 0 ? ` · ${t("photoCount", { count: photos.length })}` : ""}
          </p>
        </div>
        {isWatermarked && (
          <p className="mt-4 max-w-md text-xs text-[var(--rk-accent)]">{t("watermarkHint")}</p>
        )}
        <div className="mt-8">
          <ShareFolderPanel
            folderId={folderId}
            initialShareToken={folder.shareToken ?? null}
            initialShareTokenExpiresAt={folder.shareTokenExpiresAt ? new Date(folder.shareTokenExpiresAt).toISOString() : null}
            shareBaseUrl={`${getSiteUrl()}/${locale}/galerie`}
            labels={{
              title: t("shareTitle"),
              text: t("shareText"),
              enable: t("shareEnable"),
              disable: t("shareDisable"),
              copy: t("shareCopy"),
              copied: t("shareCopied"),
              error: t("shareError"),
              expiresOn: t("shareExpiresOn"),
              extend: t("shareExtend"),
            }}
          />
        </div>

        {photos.length > 0 && (
          <p className="mt-10 max-w-md text-sm text-[var(--rk-ink-muted)]">{t("ratingHint")}</p>
        )}
        <div className="mt-4">
          <PhotoGalleryClient folderId={folderId} photos={photos} />
        </div>
      </div>
    </div>
  );
}
