import React from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import db from '@/lib/db';
import GoBackButton from '@/components/GoBackButton';

interface ProductPageProps {
  params: Promise<{
    slug: string;
  }>;
}

export default async function ProductPage({ params }: ProductPageProps) {
  const { slug } = await params;

  const products = await db.query(`
    SELECT p.*, c.name as categoryName, c.slug as categorySlug 
    FROM Product p 
    JOIN Category c ON p.categoryId = c.id
    WHERE p.slug = ?
    LIMIT 1
  `, [slug]) as any[];

  const product = products[0];

  if (!product) {
    return notFound();
  }

  return (
    <div className="min-h-screen bg-surface">
      {/* Navigation */}
      <nav className="fixed top-0 w-full z-50 bg-white/70 backdrop-blur-xl flex justify-between items-center px-6 py-4 shadow-sm">
        <Link href="/" className="text-2xl font-serif text-emerald-900 italic tracking-tight">Marich Wellness</Link>
        <GoBackButton />
      </nav>

      <main className="pt-24 pb-32 px-6 max-w-7xl mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-16 items-start">
          {/* Image Section — sticky on desktop */}
          <div className="space-y-6 sticky top-28 self-start">
            <div className="aspect-square bg-surface-container-low rounded-[3rem] overflow-hidden shadow-2xl">
              <img 
                src={product.image || '/placeholder-product.png'} 
                alt={product.name} 
                className="w-full h-full object-cover"
              />
            </div>

            {/* Affiliate "Shop Now" button under the image */}
            {product.isAffiliate === 1 && (
              <a 
                href={product.affiliateLink || '#'} 
                target="_blank" 
                rel="noopener noreferrer"
                className="w-full block text-center bg-secondary text-white px-8 py-5 rounded-2xl font-bold text-lg hover:shadow-2xl transition-all active:scale-95 shadow-xl flex items-center justify-center gap-3"
              >
                Shop Now
                <span className="material-symbols-outlined">open_in_new</span>
              </a>
            )}
          </div>

          {/* Details Section */}
          <div className="space-y-10">
            <div>
              <div className="flex items-center gap-3 mb-4">
                <span className="px-3 py-1 bg-primary/10 text-primary text-[10px] font-bold rounded-full uppercase tracking-widest">
                  {product.categoryName}
                </span>
                {product.badge && (
                  <span className="px-3 py-1 bg-tertiary text-white text-[10px] font-bold rounded-full uppercase tracking-widest">
                    {product.badge}
                  </span>
                )}
              </div>
              <h1 className="text-5xl font-headline text-primary leading-tight">{product.name}</h1>
              <p className="text-sm text-zinc-400 mt-2 uppercase tracking-[0.2em] font-bold">{product.brand}</p>
            </div>

            <div className="text-4xl font-headline text-primary">
              ${parseFloat(product.price).toFixed(2)}
            </div>

            <div className="space-y-4">
              <h3 className="text-sm font-bold uppercase tracking-widest text-primary">Description</h3>
              <p className="text-on-surface-variant leading-relaxed text-lg italic font-serif">
                &ldquo;{product.description}&rdquo;
              </p>
            </div>

            {product.benefits && (
              <div className="space-y-4">
                <h3 className="text-sm font-bold uppercase tracking-widest text-primary">Key Benefits</h3>
                <ul className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {product.benefits.split(',').map((benefit: string, idx: number) => (
                    <li key={idx} className="flex items-center gap-3 text-sm text-on-surface-variant">
                      <span className="material-symbols-outlined text-emerald-500 text-sm">check_circle</span>
                      {benefit.trim()}
                    </li>
                  ))}
                </ul>
              </div>
            )}

            {/* Full Article Content — created via Admin Panel RichTextToolbar */}
            {product.productDescription && (
              <div className="space-y-4 pt-4 border-t border-outline-variant/10">
                <h3 className="text-sm font-bold uppercase tracking-widest text-primary">Full Article</h3>
                <div 
                  className="article-content text-on-surface-variant leading-relaxed text-base"
                  dangerouslySetInnerHTML={{ __html: product.productDescription }} 
                />
              </div>
            )}

            {/* Non-affiliate "Add to Wellness Cart" button */}
            {product.isAffiliate !== 1 && (
              <div className="pt-8 border-t border-outline-variant/10">
                <div className="flex gap-4">
                  <div className="flex-1 space-y-2">
                     <p className="text-xs text-zinc-400">Stock: <span className={product.stock < 10 ? 'text-red-500' : 'text-emerald-500'}>{product.stock} available</span></p>
                     <button className="w-full bg-primary text-on-primary px-8 py-5 rounded-2xl font-bold text-lg hover:shadow-2xl transition-all active:scale-95 shadow-xl">
                      Add to Wellness Cart
                    </button>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
