import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import Container from "@/components/Container";
import PageBanner from "@/components/PageBanner";
import ProductCard from "@/components/ProductCard";
import {
  getProduct,
  getProducts,
  productImage,
  productPriceLabel,
  stripHtml,
} from "@/lib/meshkee";

export const revalidate = 300;

export async function generateStaticParams() {
  const { items } = await getProducts({ page: 1, pageSize: 100 });
  return items.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) return {};
  return {
    title: `${product.nameFa} | آراد آریسمان`,
    description: product.summary || stripHtml(product.descriptionHtml, 160),
  };
}

export default async function ProductDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) notFound();

  const image = productImage(product);
  const shortDesc = product.summary || stripHtml(product.descriptionHtml, 160);

  const related = product.categoryId
    ? (await getProducts({ categoryId: product.categoryId, pageSize: 4 })).items
        .filter((p) => p.id !== product.id)
        .slice(0, 3)
    : [];

  return (
    <>
      <PageBanner title={product.nameFa} subtitle={shortDesc} breadcrumb={product.nameFa} />

      <section className="py-16 sm:py-20">
        <Container>
          <Link
            href="/products"
            className="inline-flex items-center gap-2 text-sm font-semibold text-primary hover:text-primary-dark transition-colors"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path
                d="M10.7 18.7a1 1 0 0 1-1.4 0l-6-6a1 1 0 0 1 0-1.4l6-6a1 1 0 1 1 1.4 1.4L6 11.3h14a1 1 0 1 1 0 2H6l4.7 4.3a1 1 0 0 1 0 1.4Z"
                fill="currentColor"
              />
            </svg>
            بازگشت به محصولات
          </Link>

          <div className="mt-8 grid grid-cols-1 lg:grid-cols-2 gap-12">
            <div className="relative aspect-square rounded-3xl overflow-hidden shadow-xl bg-surface">
              {image ? (
                <Image
                  src={image}
                  alt={product.nameFa}
                  fill
                  priority
                  className="object-cover"
                  sizes="(min-width: 1024px) 45vw, 90vw"
                />
              ) : (
                <div className="flex h-full items-center justify-center text-primary/20 text-6xl font-bold">
                  آ
                </div>
              )}
              {product.categoryNameFa && (
                <span className="absolute top-4 right-4 rounded-full bg-white/90 backdrop-blur px-4 py-1.5 text-sm font-semibold text-primary">
                  {product.categoryNameFa}
                </span>
              )}
            </div>

            <div>
              <h1 className="text-2xl sm:text-3xl font-extrabold text-primary">
                {product.nameFa}
              </h1>
              {shortDesc && (
                <p className="mt-3 text-foreground leading-8">{shortDesc}</p>
              )}

              <div className="mt-6 flex items-center gap-3">
                <span className="text-xl font-extrabold text-primary">
                  {productPriceLabel(product)}
                </span>
                {!product.store.inStock && (
                  <span className="text-sm text-foreground/60">
                    (استعلام موجودی)
                  </span>
                )}
              </div>

              <div className="mt-6 flex flex-wrap gap-3">
                <a
                  href="tel:09104067935"
                  dir="ltr"
                  className="rounded-full bg-primary px-7 py-3.5 text-white font-semibold hover:bg-primary-dark transition-colors"
                >
                  09104067935
                </a>
                <Link
                  href="/contact"
                  className="rounded-full border border-primary/30 px-7 py-3.5 text-primary font-semibold hover:bg-primary/5 transition-colors"
                >
                  استعلام قیمت
                </Link>
              </div>
            </div>
          </div>

          {product.descriptionHtml && (
            <div className="mt-14 rounded-2xl border border-black/5 bg-white p-6 sm:p-8">
              <h2 className="text-lg font-bold text-secondary">معرفی محصول</h2>
              <div
                className="rich-content mt-4"
                dangerouslySetInnerHTML={{ __html: product.descriptionHtml }}
              />
            </div>
          )}
        </Container>
      </section>

      {related.length > 0 && (
        <section className="pb-16 sm:pb-20">
          <Container>
            <h2 className="text-2xl font-extrabold text-primary">
              محصولات مرتبط
            </h2>
            <div className="mt-8 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {related.map((p) => (
                <ProductCard key={p.id} product={p} />
              ))}
            </div>
          </Container>
        </section>
      )}
    </>
  );
}
