import { prisma } from "@/lib/prisma";
import { Metadata } from "next";
import { getCache, setCache } from "@/lib/redis";
import Link from "next/link";
import BestSellersSlider from "@/components/BestSellersSlider";
import FeaturedProductsSlider from "@/components/FeaturedProductsSlider";
import TrendingCategoriesSlider from "@/components/TrendingCategoriesSlider";
import FlashSale from "@/components/FlashSale";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import RecentlyViewed from "@/components/RecentlyViewed";
import { 
  ChevronRight,
  Sparkles,
  ShieldCheck,
  RotateCcw,
  Truck,
  Mail
} from "lucide-react";
import NewsletterForm from "@/components/NewsletterForm";



export default async function Home() {
  // Fetch real categories, products, and brands from DB
  const now = new Date();
  const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);

  const CACHE_KEYS = {
    categories: "home:categories",
    products: "home:products",
    bestSellers: `home:bestSellers:${monthStart.getTime()}`,
    brands: "home:brands"
  }

  async function fetchWithCache(key: string, fetcher: () => Promise<any>, ttl = 3600) {
    const cached = await getCache(key)
    if (cached) return cached

    const freshData = await fetcher()
    await setCache(key, freshData, ttl)
    return freshData
  }

  const categories = await fetchWithCache(CACHE_KEYS.categories, () => 
    prisma.category.findMany({
      where: { parentId: null, deletedAt: null },
      include: { children: true }
    })
  );

  const products = await fetchWithCache(CACHE_KEYS.products, () => 
    prisma.product.findMany({
      where: { published: true, deletedAt: null },
      include: {
        category: true,
        brand: true,
        variants: true,
        images: true
      },
      take: 40
    })
  );

  const bestSellerItems = await fetchWithCache(CACHE_KEYS.bestSellers, () => 
    prisma.orderItem.findMany({
      where: {
        order: {
          status: { not: "CANCELLED" },
          createdAt: { gte: monthStart }
        },
        variant: {
          product: { published: true }
        }
      },
      include: {
        variant: {
          include: {
            product: {
              include: {
                category: true,
                brand: true,
                variants: true,
                images: true
              }
            }
          }
        }
      }
    })
  );

  const brands = await fetchWithCache(CACHE_KEYS.brands, () => 
    prisma.brand.findMany({
      take: 6
    })
  );

  const bestSellerTotals = new Map<string, { product: (typeof products)[number]; quantity: number }>();

  bestSellerItems.forEach((item: any) => {
    const product = item.variant.product;
    const current = bestSellerTotals.get(product.id);

    if (current) {
      current.quantity += item.quantity;
    } else {
      bestSellerTotals.set(product.id, { product, quantity: item.quantity });
    }
  });

  const bestSellerProducts = Array.from(bestSellerTotals.values())
    .sort((a, b) => b.quantity - a.quantity)
    .map((entry) => entry.product);

  // Highlighted Featured Products
  const featuredProducts = products.filter((p: any) => p.featured).slice(0, 8);
  // fallback to newest if not enough featured
  const spotlightProducts = featuredProducts.length >= 4
    ? featuredProducts
    : [...featuredProducts, ...products.filter((p: any) => !p.featured)].slice(0, 8);

  // Hero: use first 2 root categories for dual hero columns
  const heroLeft = categories[0];
  const heroRight = categories[1] || categories[0];

  const heroLeftImage = heroLeft?.image || "";
  const heroRightImage = heroRight?.image || "";

  return (
    <div className="flex flex-col min-h-screen bg-white text-zinc-950 font-sans selection:bg-zinc-900 selection:text-white antialiased">
      
      <Header categories={categories} />

      {/* 3. DYNAMIC DUAL SPLIT HERO BANNER */}
      <section className="w-full grid grid-cols-1 md:grid-cols-2 min-h-[75vh] border-b border-zinc-100">
        
        {/* Left Hero Column - first category */}
        <div className="relative group overflow-hidden flex flex-col justify-end p-8 sm:p-16 text-white min-h-[40vh] md:min-h-0 bg-zinc-900">
          {heroLeftImage && (
            <img 
              src={heroLeftImage}
              alt={heroLeft?.name || "Women's Collection"}
              className="absolute inset-0 w-full h-full object-cover object-top opacity-75 group-hover:scale-105 transition-transform duration-1000"
            />
          )}
          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent"></div>
          <div className="relative z-10 max-w-md">
            <span className="text-xs font-bold tracking-widest uppercase bg-white/20 backdrop-blur-md px-3 py-1 rounded-full mb-3 inline-block">New Collection</span>
            <h2 className="text-4xl sm:text-5xl font-extrabold tracking-tight mb-4 leading-none uppercase">{heroLeft?.name || "The New Collection"}</h2>
            <p className="text-zinc-200 text-sm sm:text-base mb-6 font-light">Explore our latest arrivals and curated styles for the season.</p>
            <div className="flex flex-wrap gap-4">
              <Link href={heroLeft ? `/category/${heroLeft.slug}` : "/shop"} className="bg-white text-zinc-950 px-6 py-3 text-xs font-bold tracking-widest uppercase hover:bg-zinc-100 transition-colors shadow-lg shadow-black/10">
                Shop {heroLeft?.name || "Now"}
              </Link>
              <Link href="/shop" className="border border-white text-white px-6 py-3 text-xs font-bold tracking-widest uppercase hover:bg-white hover:text-zinc-950 transition-all">
                View All
              </Link>
            </div>
          </div>
        </div>

        {/* Right Hero Column - second category */}
        <div className="relative group overflow-hidden flex flex-col justify-end p-8 sm:p-16 text-white min-h-[40vh] md:min-h-0 bg-zinc-800">
          {heroRightImage && (
            <img 
              src={heroRightImage}
              alt={heroRight?.name || "Men's Collection"}
              className="absolute inset-0 w-full h-full object-cover object-top opacity-75 group-hover:scale-105 transition-transform duration-1000"
            />
          )}
          <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent"></div>
          <div className="relative z-10 max-w-md">
            <span className="text-xs font-bold tracking-widest uppercase bg-white/20 backdrop-blur-md px-3 py-1 rounded-full mb-3 inline-block">Premium Styles</span>
            <h2 className="text-4xl sm:text-5xl font-extrabold tracking-tight mb-4 leading-none uppercase">{heroRight?.name || "Premium Styles"}</h2>
            <p className="text-zinc-200 text-sm sm:text-base mb-6 font-light">Discover handpicked designs crafted for the modern lifestyle.</p>
            <div className="flex flex-wrap gap-4">
              <Link href={heroRight ? `/category/${heroRight.slug}` : "/shop"} className="bg-white text-zinc-950 px-6 py-3 text-xs font-bold tracking-widest uppercase hover:bg-zinc-100 transition-colors shadow-lg shadow-black/10">
                Shop {heroRight?.name || "Now"}
              </Link>
              <Link href="/shop" className="border border-white text-white px-6 py-3 text-xs font-bold tracking-widest uppercase hover:bg-white hover:text-zinc-950 transition-all">
                Explore All
              </Link>
            </div>
          </div>
        </div>

      </section> 

      {/* FLASH SALE */}
      <FlashSale products={products} />

      {/* 7. LOVED SELLERS / BEST PRODUCTS SHOWCASE */}
      <section className="w-full py-8 sm:py-12 bg-white border-b border-zinc-100 overflow-hidden">
        <div className="max-w-7xl mx-auto px-6">
          <BestSellersSlider products={bestSellerProducts.length > 0 ? bestSellerProducts : products} />
        </div>
      </section>

      {categories.length > 0 && (
        <section className="w-full py-8 sm:py-12 bg-white border-b border-zinc-100 overflow-hidden">
          <div className="max-w-7xl mx-auto px-6">
            <TrendingCategoriesSlider categories={categories} />
          </div>
        </section>
      )}
      

      {/* 8. FEATURED PRODUCTS SLIDER (dynamic) */}
      {spotlightProducts.length > 0 && (
        <section className="w-full py-8 sm:py-12 bg-white border-b border-zinc-100 overflow-hidden">
          <div className="max-w-7xl mx-auto px-6">
            <FeaturedProductsSlider products={spotlightProducts} />
          </div>
        </section>
      )}

      {/* 9. THE BRAND SHOWCASE */}
      <section className="w-full grid grid-cols-1 md:grid-cols-2 bg-zinc-950 text-white min-h-[50vh] overflow-hidden">
        
        {/* Left Side: Editorial copywriting */}
        <div className="flex flex-col justify-center p-8 sm:p-24 max-w-xl">
          <span className="text-zinc-400 text-xs font-bold tracking-widest uppercase mb-3 block">Our Brand Collection</span>
          <h2 className="text-3xl sm:text-4xl font-extrabold tracking-tight mb-4 uppercase leading-tight">
            {brands.length > 0 ? `${brands.length} Premium Brands` : "Premium Brands"}
          </h2>
          <p className="text-zinc-300 text-sm sm:text-base mb-6 font-light leading-relaxed">
            We partner with the world&apos;s finest labels. Every piece in our collection is carefully selected, authenticity-verified, and crafted to the highest standards of luxury fashion.
          </p>
          <div className="flex items-center gap-6 mb-8 text-zinc-300 text-sm">
            <span className="flex items-center gap-1.5"><Sparkles className="w-4 h-4 text-white" /> Authentic Items</span>
            <span className="flex items-center gap-1.5"><ShieldCheck className="w-4 h-4 text-white" /> Quality Assured</span>
          </div>
          <Link href="/shop" className="bg-white text-zinc-950 px-8 py-3.5 text-xs font-bold tracking-widest uppercase hover:bg-zinc-200 transition-colors shadow-lg self-start">
            Shop All Brands
          </Link>
        </div>

        {/* Right Side: Brand grid or image */}
        <div className="relative min-h-[35vh] md:min-h-0 flex items-center justify-center p-8">
          {brands.length > 0 ? (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 w-full max-w-sm">
              {brands.map((brand: any) => (
                <div key={brand.id} className="bg-zinc-800/60 border border-zinc-700/50 rounded-xl p-4 flex items-center justify-center min-h-[80px]">
                  {brand.image ? (
                    <img src={brand.image} alt={brand.name} className="max-h-10 object-contain filter brightness-0 invert opacity-70" />
                  ) : (
                    <span className="text-zinc-300 text-xs font-bold uppercase tracking-widest text-center">{brand.name}</span>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <div className="relative w-full h-full bg-zinc-900 flex items-center justify-center">
              <span className="text-zinc-600 font-bold uppercase tracking-widest text-xs">Premium Fashion</span>
            </div>
          )}
        </div>

      </section>

      {/* 10. VALUE PROP BANNER */}
      <section className="w-full py-12 bg-zinc-900 text-white border-t border-zinc-850">
        <div className="max-w-7xl mx-auto px-6 grid grid-cols-2 md:grid-cols-4 gap-8 text-center">
          {[
            { icon: <Truck className="w-6 h-6 mx-auto mb-2 text-white" />, title: "Free Shipping", text: "On all orders over $150" },
            { icon: <RotateCcw className="w-6 h-6 mx-auto mb-2 text-white" />, title: "30-Day Returns", text: "Hassle-free dynamic returns" },
            { icon: <ShieldCheck className="w-6 h-6 mx-auto mb-2 text-white" />, title: "Secure Checkout", text: "100% encrypted checkout layers" },
            { icon: <Sparkles className="w-6 h-6 mx-auto mb-2 text-white" />, title: "Elite Quality", text: "Carefully sourced dynamic luxury materials" }
          ].map((item, idx) => (
            <div key={idx} className="flex flex-col items-center">
              {item.icon}
              <h4 className="text-xs font-bold tracking-widest uppercase mb-1">{item.title}</h4>
              <p className="text-[10px] text-zinc-400 font-light">{item.text}</p>
            </div>
          ))}
        </div>
      </section>

      {/* 11. DYNAMIC NEW ARRIVALS SECTION */}
      {products.length > 0 && (
        <section className="w-full py-8 sm:py-12 bg-white border-b border-zinc-100">
          <div className="max-w-7xl mx-auto px-6">
            
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-end mb-10 gap-4">
              <div>
                <h2 className="text-2xl sm:text-3xl font-extrabold tracking-tight uppercase">New Arrivals</h2>
                <p className="text-zinc-500 text-sm mt-1 font-light">The freshest additions to our collection — just landed.</p>
              </div>
              <Link href="/shop?sort=newest" className="text-xs font-bold tracking-widest uppercase text-zinc-950 hover:text-zinc-600 transition-colors flex items-center gap-1 group">
                View All <ChevronRight className="w-4 h-4 group-hover:translate-x-1 transition-transform" />
              </Link>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 sm:gap-6">
              {products.slice(0, 4).map((product: any) => {
                const img = product.images?.[0]?.url || "";
                const price = product.variants?.[0]?.price ?? product.basePrice;
                return (
                  <Link key={product.id} href={`/product/${product.slug}`} className="group flex flex-col">
                    <div className="relative aspect-[3/4] overflow-hidden bg-zinc-100 mb-3 border border-zinc-100">
                      {img && (
                        <img
                          src={img}
                          alt={product.title}
                          className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-700"
                        />
                      )}
                      {product.featured && (
                        <span className="absolute top-3 left-3 bg-zinc-950 text-white text-[9px] font-bold uppercase tracking-widest px-2 py-1">
                          Featured
                        </span>
                      )}
                    </div>
                    <h3 className="text-xs font-bold uppercase tracking-wider text-zinc-900 group-hover:text-zinc-500 transition-colors line-clamp-1">{product.title}</h3>
                    <p className="text-xs text-zinc-500 mt-0.5">{product.category?.name}</p>
                    <p className="text-sm font-bold mt-1 text-zinc-900">${Number(price).toFixed(2)}</p>
                  </Link>
                );
              })}
            </div>

          </div>
        </section>
      )}

      {/* 12. EMAIL NEWSLETTER CARD */}
      <section className="w-full bg-zinc-50 py-8 sm:py-12 border-b border-zinc-100">
        <div className="max-w-4xl mx-auto px-6 text-center">
          <Mail className="w-8 h-8 mx-auto mb-6 text-zinc-800" />
          <h2 className="text-2xl sm:text-3xl font-extrabold tracking-tight uppercase mb-4">Elevate Your Wardrobe</h2>
          <p className="text-zinc-500 text-sm sm:text-base font-light mb-8 max-w-md mx-auto">
            Subscribe to our newsletter for exclusive styling guides, new collection alerts, and 15% off your first online order.
          </p>
          <NewsletterForm />
        </div>
      </section>
      {/* RECENTLY VIEWED */}
      <RecentlyViewed currentProductId="" />

      <Footer categories={categories} />

    </div>
  );
}
