import Link from "next/link";
import type { Metadata } from "next";
import { ProductCard } from "@/components/store/product-card";
import { listSanityProductCategories, listSanityProducts, listSanityProductsByCategory } from "@/lib/sanity/queries";
import { getResolvedSiteText } from "@/lib/site-text-server";
import { text } from "@/lib/site-text";
import { env } from "@/lib/env";

export const metadata: Metadata = {
  title: "Boutique",
  description: "Parcourez tous les produits Stylunique et trouvez la création personnalisée idéale.",
  alternates: {
    canonical: "/boutique",
  },
};

type Props = {
  searchParams: Promise<{ categorie?: string }>;
};

export default async function BoutiquePage({ searchParams }: Props) {
  const { categorie } = await searchParams;
  const selectedCategorySlug = (categorie || "").trim();

  const [categories, products, siteText] = await Promise.all([
    listSanityProductCategories(30),
    selectedCategorySlug ? listSanityProductsByCategory(selectedCategorySlug, 60) : listSanityProducts(60),
    getResolvedSiteText(),
  ]);

  const selectedCategory = categories.find((category) => category.slug === selectedCategorySlug);

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Accueil",
        item: env.siteUrl,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: selectedCategory ? selectedCategory.title : "Tous les produits",
        item: selectedCategorySlug
          ? `${env.siteUrl}/boutique?categorie=${encodeURIComponent(selectedCategorySlug)}`
          : `${env.siteUrl}/boutique`,
      },
    ],
  };

  return (
    <div className="space-y-8">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }} />
      <header className="rounded-[1.9rem] border border-[#ffdede] bg-[linear-gradient(135deg,#fffafa_0%,#fff0f0_55%,#ffe7e7_100%)] p-6 shadow-[0_20px_42px_rgba(49,18,18,0.1)] md:p-8">
        <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--accent-3)]">{text(siteText, "shop.eyebrow")}</p>
        <h1 className="mt-2 font-serif text-5xl text-[var(--foreground)] md:text-6xl">
          {selectedCategory ? selectedCategory.title : text(siteText, "shop.title.all")}
        </h1>
        <p className="mt-3 max-w-2xl text-[var(--muted)]">
          {selectedCategory
            ? `${text(siteText, "shop.description.categoryPrefix")} ${selectedCategory.title}.`
            : text(siteText, "shop.description.all")}
        </p>
      </header>

      <div className="flex flex-wrap gap-2 text-xs font-semibold uppercase tracking-[0.12em] text-[var(--accent-3)]">
        <Link
          href="/boutique"
          className={`rounded-full border px-3 py-1.5 ${
            selectedCategorySlug
              ? "border-[#ffd8d8] bg-white/80"
              : "border-[var(--accent)] bg-[var(--accent)] text-white"
          }`}
        >
          {text(siteText, "shop.filter.all")}
        </Link>
        {categories.map((category) => {
          const active = category.slug === selectedCategorySlug;
          return (
            <Link
              key={category._id}
              href={`/boutique?categorie=${encodeURIComponent(category.slug)}`}
              className={`rounded-full border px-3 py-1.5 ${
                active ? "border-[var(--accent)] bg-[var(--accent)] text-white" : "border-[#ffd8d8] bg-white/80"
              }`}
            >
              {category.title}
            </Link>
          );
        })}
      </div>

      {products.length > 0 ? (
        <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {products.map((product, index) => (
            <ProductCard key={product._id} product={product} index={index} />
          ))}
        </section>
      ) : (
        <p className="rounded-2xl border border-[#ffe1e1] bg-[var(--surface)] p-5 text-sm text-[var(--muted)]">
          {text(siteText, "shop.empty")}
        </p>
      )}
    </div>
  );
}
