import { notFound } from "next/navigation";
import Link from "next/link";
import { getProductBySlug } from "@/lib/queries";
import Header from "@/components/header";
import Footer from "@/components/footer";
import ProductGallery from "@/components/productGallery";
import ProductPurchasePanel from "@/components/productPurchasePanel";
import ProductCard from "@/components/productCard";
import ProductTabs from "@/components/productTabs";
import ReviewForm from "@/components/reviewForm";
import CountdownTimer from "@/components/countdownTimer";
import { Zap } from "lucide-react";

// then use: priceDelta: Prisma.Decimal;
// then use: priceDelta: Prisma.Decimal;

export default async function ProductPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const data = await getProductBySlug(slug);

  if (!data) {
    notFound();
  }

  const { product, relatedProducts } = data;

  const basePrice = Number(product.basePrice);
  const compareAtPrice = product.compareAtPrice ? Number(product.compareAtPrice) : null;

  const reviewCount = product.reviews?.length ?? 0;
  const avgRating =
    reviewCount > 0
      ? product.reviews.reduce((sum: number, r: any) => sum + r.rating, 0) / reviewCount
      : 0;

  const activeDeal = product.deals?.[0]?.deal ?? null;
  const saleEndsAt = activeDeal?.endsAt ?? null;

  const headerBlock = (
    <>
      {product.brand && (
        <span className="text-xs text-ink/50 font-mono uppercase tracking-wide">
          {product.brand.name}
        </span>
      )}
      <h1 className="font-display text-2xl font-bold text-ink">{product.name}</h1>

      <div className="flex items-center gap-2 flex-wrap">
        {product.condition === "REFURBISHED" && (
          <span className="bg-gold text-white text-xs font-mono px-2 py-1 rounded">
            Refurbished
          </span>
        )}
        {product.condition === "NEW" && (
          <span className="bg-harbor text-white text-xs font-mono px-2 py-1 rounded">
            Brand New
          </span>
        )}
        <span className="text-xs text-ink/50">{product.warrantyMonths}-month warranty</span>
      </div>

      {reviewCount > 0 && (
        <div className="flex items-center gap-2 text-sm">
          <span className="text-gold font-mono">
            {"★".repeat(Math.round(avgRating))}
            {"☆".repeat(5 - Math.round(avgRating))}
          </span>
          <span className="text-ink/50">
            {avgRating.toFixed(1)} ({reviewCount} review{reviewCount !== 1 ? "s" : ""})
          </span>
        </div>
      )}
    </>
  );

  const descriptionBlock = (
    <p className="text-sm text-ink/70 leading-relaxed border-t border-line pt-4 mt-2 line-clamp-3">
      {product.description}
    </p>
  );

  const countdownBlock = saleEndsAt ? (
    <div className="flex items-center justify-between bg-harbor text-white rounded-md px-3 py-2">
      <span className="flex items-center gap-2 text-sm font-semibold">
        <Zap size={16} className="text-coral" />
        Limited offer
      </span>
      <CountdownTimer endsAt={saleEndsAt} />
    </div>
  ) : null;

  const paymentBlock = (
    <div className="border-t border-line pt-4 flex flex-col gap-2 text-xs text-ink/50">
      <p className="font-medium text-ink/70">Accepted payment methods</p>
      <div className="flex flex-wrap gap-2">
        <span className="border border-line rounded px-2 py-1">M-Pesa</span>
        <span className="border border-line rounded px-2 py-1">Visa</span>
        <span className="border border-line rounded px-2 py-1">Mastercard</span>
        <span className="border border-line rounded px-2 py-1">Cash on Delivery</span>
      </div>
      <p className="mt-2">
        Secure checkout · {product.warrantyMonths}-month warranty included
      </p>
    </div>
  );

  const sellerBlock = product.vendor ? (
    <div className="border-t border-line pt-4 flex flex-col gap-3">
      <div className="flex items-center justify-between">
        <span className="font-display font-bold text-ink text-sm">{product.vendor.name}</span>
        <span className="text-xs text-ink/50">
          Score <span className="text-harbor font-semibold">{Number(product.vendor.score)}</span>
        </span>
      </div>
      <div className="flex gap-2">
        <Link
          href={`/store/${product.vendor.slug}`}
          className="flex-1 text-center text-sm font-semibold border border-line rounded-md py-2 hover:border-harbor transition-colors"
        >
          Visit Store
        </Link>
        <button className="flex-1 text-sm font-semibold border border-line rounded-md py-2 hover:border-harbor transition-colors">
          Chat Seller
        </button>
      </div>
    </div>
  ) : null;

  // ✅ Fixed: Added type annotation for 'v'
  const variants = product.variants.map((v) => ({
  id: v.id,
  name: v.name,
  priceDelta: Number(v.priceDelta),
  stockQty: v.stockQty,
  isDefault: v.isDefault,
})); 
 /* const variants = product.variants.map((v: {
    id: string;
    name: string;
    priceDelta: number;
    stockQty: number;
    isDefault: boolean;
  }) => ({
    id: v.id,
    name: v.name,
    priceDelta: Number(v.priceDelta),
    stockQty: v.stockQty,
    isDefault: v.isDefault,
  }));*/

  return (
    <>
      <Header />
      <section className="max-w-7xl mx-auto px-4 py-8">
        <nav className="text-sm text-ink/50 mb-6 font-mono">
          <Link href="/" className="hover:text-harbor">Home</Link>
          {" / "}
          <Link href={`/catalogue/${product.category.slug}`} className="hover:text-harbor">
            {product.category.name}
          </Link>
          {" / "}
          <span className="text-ink">{product.name}</span>
        </nav>

        <div
          className="grid gap-x-10 gap-y-16 lg:grid-cols-[1fr_1fr_380px]"
          style={{
            gridTemplateAreas: `"gallery details panel" "tabs tabs panel"`,
          }}
        >
          <div style={{ gridArea: "gallery" }}>
            <ProductGallery images={product.images} productName={product.name} />
          </div>

          <ProductPurchasePanel
            productId={product.id}
            productName={product.name}
            basePrice={basePrice}
            compareAtPrice={compareAtPrice}
            warrantyMonths={product.warrantyMonths}
            variants={variants}
            headerBlock={headerBlock}
            descriptionBlock={descriptionBlock}
            countdownBlock={countdownBlock}
            paymentBlock={paymentBlock}
            sellerBlock={sellerBlock}
          />

          <div style={{ gridArea: "tabs" }}>
            <ProductTabs
              description={product.description}
              specs={product.specs}
              warrantyMonths={product.warrantyMonths}
              reviews={product.reviews}
              reviewFormSlot={<ReviewForm productId={product.id} productSlug={product.slug} />}
            />
          </div>
        </div>

        {relatedProducts.length > 0 && (
          <div className="mt-16">
            <h2 className="font-display text-xl font-bold text-ink mb-6">
              You might also like
            </h2>
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-4">
              {relatedProducts.map((p, index) => (
                <ProductCard key={p.slug} product={p} index={index} />
              ))}
            </div>
          </div>
        )}
      </section>
      <Footer />
    </>
  );
}