import { db } from "@/lib/db";
import { products } from "@/lib/db/schema";
import { eq, ne, and } from "drizzle-orm";
import { notFound } from "next/navigation";
import Link from "next/link";
import CheckoutButton from "@/components/CheckoutButton";

export const dynamic = "force-dynamic";

export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const product = (await db.select().from(products).where(eq(products.slug, slug)))[0];
  if (!product) return notFound();

  const related = await db
    .select()
    .from(products)
    .where(and(ne(products.id, product.id), eq(products.status, "published")))
    .limit(4);

  const hasDiscount = product.compareAtPrice && product.compareAtPrice > (product.price || 0);
  const discountPct = hasDiscount ? Math.round(100 - ((product.price || 0) / product.compareAtPrice!) * 100) : 0;

  // Description may contain manual line breaks — render as real paragraphs.
  const descriptionParagraphs = (product.description || "").split(/\n+/).filter(Boolean);

  return (
    <div className="max-w-6xl mx-auto">
      <nav className="text-xs text-neutral-500 mb-6">
        <Link href="/shop" className="hover:text-white">Shop</Link>
        <span className="mx-2">/</span>
        <span className="text-neutral-300">{product.title}</span>
      </nav>

      <div className="grid md:grid-cols-2 gap-10 mb-16">
        {/* Image */}
        <div>
          <div className="aspect-square bg-neutral-900 rounded-xl overflow-hidden border border-neutral-800 relative">
            {product.imageUrl ? (
              <img src={product.imageUrl} className="w-full h-full object-cover" alt={product.title} />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-6xl opacity-20">📦</div>
            )}
            {hasDiscount && (
              <span className="absolute top-4 left-4 bg-red-600 text-white text-xs font-bold px-3 py-1 rounded-full">
                {discountPct}% OFF
              </span>
            )}
            {product.featured && (
              <span className="absolute top-4 right-4 bg-amber-500 text-black text-xs font-bold px-3 py-1 rounded-full">
                ★ Featured
              </span>
            )}
          </div>
        </div>

        {/* Details */}
        <div className="flex flex-col">
          <span className="text-xs uppercase tracking-wide text-neutral-500 font-semibold mb-2">
            {product.type === "digital" ? "Digital Product" : product.type === "physical" ? "Ships to You" : "Recommended Resource"}
          </span>
          <h1 className="text-3xl font-bold mb-4">{product.title}</h1>

          <div className="flex items-baseline gap-3 mb-6">
            {hasDiscount && (
              <span className="line-through text-neutral-500 text-lg">${product.compareAtPrice!.toFixed(2)}</span>
            )}
            <span className="text-3xl font-bold text-white">${(product.price || 0).toFixed(2)}</span>
            {hasDiscount && <span className="text-sm text-emerald-400 font-semibold">Save {discountPct}%</span>}
          </div>

          {descriptionParagraphs.length > 0 && (
            <div className="mb-6 space-y-3">
              {descriptionParagraphs.map((para, i) => (
                <p key={i} className="text-neutral-300 leading-relaxed">{para}</p>
              ))}
            </div>
          )}

          <div className="card p-4 mb-6 bg-neutral-900/50 space-y-2 text-sm">
            <div className="flex items-center gap-2 text-neutral-400">
              <span className="text-emerald-500">✓</span>
              {product.type === "digital"
                ? "Instant access after purchase"
                : product.type === "physical"
                ? "Ships within a few business days"
                : "Trusted recommendation from our team"}
            </div>
            <div className="flex items-center gap-2 text-neutral-400">
              <span className="text-emerald-500">✓</span>
              Secure checkout via Stripe
            </div>
            {product.type === "digital" && (
              <div className="flex items-center gap-2 text-neutral-400">
                <span className="text-emerald-500">✓</span>
                Access anytime from My Library
              </div>
            )}
          </div>

          <div className="mt-auto">
            {product.type === "affiliate" && product.affiliateUrl ? (
              <a href={product.affiliateUrl} target="_blank" rel="noopener noreferrer" className="btn-primary inline-block px-8 py-3.5 text-center w-full sm:w-auto">
                View on Retailer's Site →
              </a>
            ) : (
              <CheckoutButton
                type="purchase"
                label={`Buy for $${(product.price || 0).toFixed(2)}`}
                amount={product.price || 0}
                description={product.title}
                metadata={{ productId: product.id }}
                productId={product.id}
                imageUrl={product.imageUrl || undefined}
                className="btn-primary px-8 py-3.5 w-full sm:w-auto"
              />
            )}
          </div>
        </div>
      </div>

      {related.length > 0 && (
        <div>
          <h2 className="text-lg font-bold mb-4">You May Also Like</h2>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            {related.map((p) => (
              <Link key={p.id} href={`/shop/${p.slug}`} className="card overflow-hidden hover:border-neutral-600 transition-colors">
                <div className="aspect-square bg-neutral-900 flex items-center justify-center">
                  {p.imageUrl ? (
                    <img src={p.imageUrl} className="w-full h-full object-cover" alt={p.title} />
                  ) : (
                    <span className="text-3xl opacity-20">📦</span>
                  )}
                </div>
                <div className="p-3">
                  <h3 className="font-semibold text-xs mb-1 line-clamp-1">{p.title}</h3>
                  <p className="text-sm font-bold">${(p.price || 0).toFixed(2)}</p>
                </div>
              </Link>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
