import Link from "next/link";
import Image from "next/image";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { isLocale, type Locale } from "@/lib/i18n/config";
import { getDictionary } from "@/lib/i18n";
import { getCategoryBySlug, getProducts } from "@/lib/catalog";
import { collections, getCollection } from "@/lib/collections";
import { buildMetadata } from "@/lib/seo";
import { Button } from "@/components/ui/button";
import { ProductCard } from "@/components/store/product-card";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale: raw, slug } = await params;
  if (!isLocale(raw)) return {};
  const locale = raw as Locale;
  const collection = getCollection(slug);
  if (!collection) return {};
  const dict = getDictionary(locale);
  const text = collection.texts[locale];
  return buildMetadata({
    locale,
    title: `${text.title} — ${dict.collections.title}`,
    description: text.description,
    path: `/collections/${slug}`,
    image: collection.image,
  });
}

export function generateStaticParams() {
  return collections.map((collection) => ({ slug: collection.slug }));
}

export default async function CollectionPage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale: raw, slug } = await params;
  if (!isLocale(raw)) notFound();
  const locale = raw as Locale;
  const dict = getDictionary(locale);
  const collection = getCollection(slug);
  if (!collection) {
    // Category links used to point at /collections/{category}, so send those
    // to the shop's category listing instead of showing a 404.
    const category = await getCategoryBySlug(slug);
    if (category) redirect(`/${locale}/shop?category=${slug}`);
    notFound();
  }

  const text = collection.texts[locale];
  const results = await getProducts({
    q: "",
    category: collection.category ?? "",
    min: undefined,
    max: undefined,
    inStock: false,
    featured: collection.featured ?? false,
    sort: "featured",
    page: 1,
  });

  return (
    <>
      <section className="relative overflow-hidden bg-charcoal">
        <div className="absolute inset-0">
          <Image src={collection.image} alt={text.title} fill priority sizes="100vw" className="object-cover opacity-45" />
        </div>
        <div className="shell relative flex min-h-[420px] flex-col justify-end py-14 text-ivory md:min-h-[500px] md:py-20">
          <Link
            href={`/${locale}/collections`}
            className="mb-10 inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.18em] text-ivory/55 hover:text-ivory"
          >
            <ArrowLeft className="h-3.5 w-3.5 rtl:rotate-180" />
            {dict.collections.back}
          </Link>
          <p className="eyebrow text-gold">{dict.nav.collections}</p>
          <h1 className="mt-4 max-w-3xl font-serif text-5xl font-light leading-[1.02] tracking-tight md:text-7xl">
            {text.title}
          </h1>
          <p className="mt-5 max-w-xl text-[15px] leading-relaxed text-ivory/65">{text.story}</p>
        </div>
      </section>

      <div className="shell py-14 md:py-20">
        <div className="flex items-center justify-between gap-6 border-b border-border pb-5">
          <p className="text-[12px] uppercase tracking-[0.14em] text-charcoal/45">
            {results.total} {dict.shop.productsCount}
          </p>
          <Link
            href={`/${locale}/shop`}
            className="text-[12px] uppercase tracking-[0.14em] text-charcoal/50 hover:text-charcoal"
          >
            {dict.shop.title}
          </Link>
        </div>

        {results.items.length === 0 ? (
          <div className="py-20 text-center">
            <p className="font-serif text-2xl">{dict.collections.empty}</p>
            <Button asChild variant="outline" className="mt-6">
              <Link href={`/${locale}/shop`}>{dict.shop.title}</Link>
            </Button>
          </div>
        ) : (
          <div className="mt-8 grid grid-cols-2 gap-x-4 gap-y-10 md:grid-cols-4 md:gap-x-6">
            {results.items.map((product) => (
              <ProductCard
                key={product.id}
                product={product}
                locale={locale}
                dict={dict}
                titleClassName="text-[20px] md:text-2xl"
              />
            ))}
          </div>
        )}
      </div>
    </>
  );
}
