import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";

import { GlassCard } from "@/components/shared/glass-card";
import { getTransformations } from "@/lib/data/transformations";
import { buildCmsPageMetadata } from "@/lib/seo/page-metadata";

export const revalidate = 120;

export async function generateMetadata(): Promise<Metadata> {
  return buildCmsPageMetadata(
    "gallery",
    "Transformation Gallery",
    "Before and after highlights from disciplined athletes inside the systems.",
    "/gallery",
  );
}

const GALLERY_OMIT_LAST = 5;
const GALLERY_PAGE_SIZE = 18;

function pageFromSearchParams(value: string | string[] | undefined) {
  const raw = Array.isArray(value) ? value[0] : value;
  const page = Number(raw ?? "1");
  return Number.isFinite(page) ? Math.max(1, Math.floor(page)) : 1;
}

function galleryPageHref(page: number) {
  return page <= 1 ? "/gallery" : `/gallery?page=${page}`;
}

export default async function GalleryPage({
  searchParams,
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const page = pageFromSearchParams(params?.page);
  const all = await getTransformations();
  const visibleTransformations =
    all.length > GALLERY_OMIT_LAST ? all.slice(0, all.length - GALLERY_OMIT_LAST) : all;
  const totalPages = Math.max(1, Math.ceil(visibleTransformations.length / GALLERY_PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const transformations = visibleTransformations.slice(
    (currentPage - 1) * GALLERY_PAGE_SIZE,
    currentPage * GALLERY_PAGE_SIZE,
  );
  const omitted = all.length - visibleTransformations.length;
  return (
    <div className="ds-container ds-section">
      <h1 className="font-display text-4xl tracking-tight sm:text-5xl">Gallery</h1>
      <p className="mt-4 text-sm text-muted-foreground">
        Showing {transformations.length} of {visibleTransformations.length} transformation
        {visibleTransformations.length === 1 ? "" : "s"}
        {omitted > 0 ? (
          <>
            {" "}
            ({omitted} last {omitted === 1 ? "entry" : "entries"} in the list omitted — still in site content).
          </>
        ) : null}
      </p>
      <div className="mt-14 grid gap-6 sm:grid-cols-2 xl:grid-cols-3">
        {transformations.map((t, index) => (
          <GlassCard key={t.id} className="flex h-full flex-col overflow-hidden p-0">
            {t.collageSrc ? (
              <div className="relative aspect-square bg-black">
                <Image
                  src={t.collageSrc}
                  alt={t.title}
                  fill
                  className="object-cover object-top"
                  sizes="(max-width:640px) 100vw, (max-width:1280px) 50vw, 33vw"
                  priority={currentPage === 1 && index < 2}
                />
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-1 bg-black">
                <div className="relative aspect-[3/4]">
                  <Image
                    src={t.beforeSrc ?? ""}
                    alt={`${t.title} before`}
                    fill
                    className="object-cover object-top"
                    sizes="(max-width:640px) 50vw, 25vw"
                    priority={currentPage === 1 && index === 0}
                  />
                </div>
                <div className="relative aspect-[3/4]">
                  <Image
                    src={t.afterSrc ?? ""}
                    alt={`${t.title} after`}
                    fill
                    className="object-cover object-top"
                    sizes="(max-width:640px) 50vw, 25vw"
                    priority={currentPage === 1 && index === 0}
                  />
                </div>
              </div>
            )}
            <div className="flex flex-1 flex-col gap-2 p-5">
              {t.clientName ? (
                <p className="text-xs font-semibold uppercase tracking-widest text-primary">{t.clientName}</p>
              ) : null}
              <p className="font-display text-xl leading-snug">{t.title}</p>
              <p className="text-xs text-muted-foreground">{t.timeframe}</p>
              {t.description ? (
                <p className="mt-1 flex-1 text-sm leading-relaxed text-muted-foreground">{t.description}</p>
              ) : null}
            </div>
          </GlassCard>
        ))}
      </div>
      {totalPages > 1 ? (
        <div className="mt-10 flex items-center justify-between text-sm">
          <Link
            href={galleryPageHref(Math.max(1, currentPage - 1))}
            aria-disabled={currentPage <= 1}
            className="rounded-lg border border-white/10 px-3 py-2 text-muted-foreground aria-disabled:pointer-events-none aria-disabled:opacity-40"
          >
            Previous
          </Link>
          <span className="text-muted-foreground">
            Page {currentPage} of {totalPages}
          </span>
          <Link
            href={galleryPageHref(Math.min(totalPages, currentPage + 1))}
            aria-disabled={currentPage >= totalPages}
            className="rounded-lg border border-white/10 px-3 py-2 text-muted-foreground aria-disabled:pointer-events-none aria-disabled:opacity-40"
          >
            Next
          </Link>
        </div>
      ) : null}
    </div>
  );
}
