import Link from "next/link";
import { notFound } from "next/navigation";
import { Check, MessageCircle, Star } from "lucide-react";
import { ProductCard } from "@/components/store/product-card";
import { Button } from "@/components/ui/button";
import { Badge, SectionHeading } from "@/components/ui/section";
import { JsonLd } from "@/components/seo/json-ld";
import { breadcrumbJsonLd, buildMetadata, productJsonLd } from "@/lib/seo";
import { formatCurrency } from "@/lib/utils";
import { productService } from "@/services/catalog.service";
import { settingsRepository } from "@/repositories";
import { ProductGallery } from "./product-gallery";
import { AddToCartButton } from "./add-to-cart-button";

export const dynamic = "force-dynamic";

type Params = Promise<{ slug: string }>;

export async function generateMetadata({ params }: { params: Params }) {
  const { slug } = await params;
  const product = await productService.getBySlug(slug);
  if (!product) return buildMetadata({ title: "Produk tidak ditemukan", path: `/product/${slug}`, noIndex: true });
  return buildMetadata({
    title: product.metaTitle || product.name,
    description: product.metaDescription || product.shortDescription,
    path: `/product/${product.slug}`,
    image: product.thumbnail,
    type: "product",
  });
}

export default async function ProductDetailPage({ params }: { params: Params }) {
  const { slug } = await params;
  const [product, whatsapp] = await Promise.all([
    productService.getBySlug(slug),
    settingsRepository.get("whatsapp"),
  ]);

  if (!product) notFound();

  const phone = (whatsapp || "6281234567890").replace(/\D/g, "");
  const waMessage = `Halo 305 Gaming, saya ingin order: ${product.name} (${product.sku})`;
  const waHref = `https://wa.me/${phone}?text=${encodeURIComponent(waMessage)}`;
  const images = [product.thumbnail, ...product.gallery].filter(Boolean) as string[];

  return (
    <div className="container-shell pt-28 pb-16">
      <JsonLd
        data={[
          productJsonLd(product),
          breadcrumbJsonLd([
            { name: "Beranda", path: "/" },
            { name: "Produk", path: "/products" },
            ...(product.category
              ? [{ name: product.category.name, path: `/category/${product.category.slug}` }]
              : []),
            { name: product.name, path: `/product/${product.slug}` },
          ]),
        ]}
      />

      <nav className="mb-8 text-sm text-muted">
        <Link href="/" className="hover:text-text">
          Beranda
        </Link>
        <span className="mx-2">/</span>
        <Link href="/products" className="hover:text-text">
          Produk
        </Link>
        {product.category ? (
          <>
            <span className="mx-2">/</span>
            <Link href={`/category/${product.category.slug}`} className="hover:text-text">
              {product.category.name}
            </Link>
          </>
        ) : null}
        <span className="mx-2">/</span>
        <span className="text-text">{product.name}</span>
      </nav>

      <div className="grid gap-10 lg:grid-cols-2">
        <ProductGallery images={images} name={product.name} />

        <div>
          <div className="flex flex-wrap gap-2">
            {product.isTrending ? <Badge>Trending</Badge> : null}
            {product.isBestSeller ? <Badge className="bg-white/10 text-white">Best Seller</Badge> : null}
            {product.category ? (
              <Badge className="bg-white/5 text-muted">{product.category.name}</Badge>
            ) : null}
          </div>

          <h1 className="mt-4 font-[family-name:var(--font-space)] text-3xl font-bold tracking-tight md:text-4xl">
            {product.name}
          </h1>

          <div className="mt-3 flex items-center gap-2 text-sm text-muted">
            <Star className="h-4 w-4 fill-accent text-accent" />
            <span>{product.ratingAvg.toFixed(1)}</span>
            <span>({product.ratingCount} ulasan)</span>
            <span>·</span>
            <span>{product.soldCount} terjual</span>
          </div>

          <div className="mt-6 flex items-end gap-3">
            <p className="font-[family-name:var(--font-space)] text-3xl font-bold text-accent">
              {formatCurrency(product.price)}
            </p>
            {product.compareAtPrice && product.compareAtPrice > product.price ? (
              <p className="pb-1 text-sm text-muted line-through">{formatCurrency(product.compareAtPrice)}</p>
            ) : null}
          </div>

          {product.shortDescription ? (
            <p className="mt-4 text-muted leading-relaxed">{product.shortDescription}</p>
          ) : null}

          <div className="mt-8 flex flex-wrap gap-3">
            <AddToCartButton
              product={{
                id: product.id,
                name: product.name,
                slug: product.slug,
                price: product.price,
                thumbnail: product.thumbnail,
              }}
            />
            <Button href={waHref} variant="secondary" size="lg">
              <MessageCircle className="h-4 w-4" />
              Order via WhatsApp
            </Button>
          </div>

          <p className="mt-4 text-xs text-muted">
            SKU: {product.sku} · Stok: {product.stock > 0 ? `${product.stock} tersedia` : "Habis"}
          </p>

          {product.features.length ? (
            <ul className="mt-8 space-y-3 rounded-2xl border border-border bg-surface p-5">
              {product.features.map((feature) => (
                <li key={feature} className="flex items-start gap-3 text-sm">
                  <Check className="mt-0.5 h-4 w-4 shrink-0 text-accent" />
                  <span>{feature}</span>
                </li>
              ))}
            </ul>
          ) : null}
        </div>
      </div>

      {product.description ? (
        <section className="mt-14 max-w-3xl">
          <SectionHeading title="Deskripsi" />
          <div className="mt-4 whitespace-pre-line text-muted leading-relaxed">{product.description}</div>
        </section>
      ) : null}

      {product.reviews?.length ? (
        <section className="mt-14">
          <SectionHeading title="Ulasan pembeli" description={`${product.reviews.length} ulasan terbaru`} />
          <div className="mt-6 grid gap-4 md:grid-cols-2">
            {product.reviews.map((review) => (
              <article key={review.id} className="rounded-2xl border border-border bg-surface p-5">
                <div className="flex items-center justify-between gap-3">
                  <p className="font-semibold">{review.authorName}</p>
                  <div className="flex items-center gap-1 text-xs text-muted">
                    <Star className="h-3.5 w-3.5 fill-accent text-accent" />
                    {review.rating}
                  </div>
                </div>
                {review.comment ? <p className="mt-3 text-sm text-muted">{review.comment}</p> : null}
              </article>
            ))}
          </div>
        </section>
      ) : null}

      {product.related.length ? (
        <section className="mt-16">
          <SectionHeading title="Produk terkait" description="Rekomendasi serupa untuk Anda" />
          <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {product.related.map((item) => (
              <ProductCard key={item.id} product={item} />
            ))}
          </div>
        </section>
      ) : null}
    </div>
  );
}
