import Link from "next/link";
import { ArrowRight, Bot, Star, Zap, TrendingUp } from "lucide-react";
import HeroBanner from "@/components/home/HeroBanner";
import CategorySection from "@/components/home/CategorySection";
import ProductGrid from "@/components/products/ProductGrid";
import type { ProductCardData } from "@/components/products/ProductCard";
import { prisma } from "@/lib/prisma";
import { serialize } from "@/lib/serialize";

async function getFeaturedProducts(): Promise<ProductCardData[]> {
  try {
    const products = await prisma.product.findMany({
      where: { featured: true, status: "ACTIVE" },
      include: { brand: true, category: true, reviews: { select: { rating: true } } },
      take: 8, orderBy: { createdAt: "desc" },
    });
    return serialize(products) as unknown as ProductCardData[];
  } catch { return []; }
}

async function getNewArrivals(): Promise<ProductCardData[]> {
  try {
    const products = await prisma.product.findMany({
      where: { isNew: true, status: "ACTIVE" },
      include: { brand: true, category: true, reviews: { select: { rating: true } } },
      take: 8, orderBy: { createdAt: "desc" },
    });
    return serialize(products) as unknown as ProductCardData[];
  } catch { return []; }
}

async function getDeals(): Promise<ProductCardData[]> {
  try {
    const products = await prisma.product.findMany({
      where: { status: "ACTIVE", comparePrice: { not: null } },
      include: { brand: true, category: true, reviews: { select: { rating: true } } },
      take: 4, orderBy: { createdAt: "desc" },
    });
    return serialize(products) as unknown as ProductCardData[];
  } catch { return []; }
}

export default async function HomePage() {
  const [featured, newArrivals, deals] = await Promise.all([
    getFeaturedProducts(),
    getNewArrivals(),
    getDeals(),
  ]);

  const heroProducts = featured.slice(0, 3);

  return (
    <main>
      <HeroBanner products={heroProducts} />

      {/* Featured Products — first section after hero */}
      <section className="py-10 bg-slate-50">
        <div className="max-w-7xl mx-auto px-4">
          <div className="flex items-center justify-between mb-6">
            <div className="flex items-center gap-3">
              <div className="w-1 h-8 bg-sky-500 rounded-full" />
              <div>
                <h2 className="text-2xl font-black text-slate-900">Featured Products</h2>
                <p className="text-slate-500 text-sm">Hand-picked best sellers</p>
              </div>
            </div>
            <Link href="/products?featured=true" className="flex items-center gap-1 text-sky-600 hover:text-sky-700 text-sm font-semibold">
              View All <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
          {featured.length > 0 ? (
            <ProductGrid products={featured} cols={4} />
          ) : (
            <div className="text-center py-12 text-slate-400">
              <p className="text-5xl mb-3">💻</p>
              <p className="text-lg font-medium">Products coming soon!</p>
              <p className="text-sm mt-1">Our team is adding the best products for you.</p>
            </div>
          )}
        </div>
      </section>

      <CategorySection />

      {/* Promo strip */}
      <div className="bg-gradient-to-r from-sky-700 via-sky-600 to-blue-700 text-white py-3">
        <div className="max-w-7xl mx-auto px-4 flex flex-wrap items-center justify-center gap-4 sm:gap-8 text-xs sm:text-sm text-center">
          <span className="flex items-center gap-2 font-medium">
            <Zap className="w-4 h-4 text-yellow-300" /> Flash Sale — Up to 40% OFF
          </span>
          <span className="hidden sm:block text-white/40">|</span>
          <span className="font-medium">🚚 Free delivery above KES 10,000</span>
          <span className="hidden sm:block text-white/40">|</span>
          <span className="font-medium">💳 Pay in installments</span>
        </div>
      </div>

      {/* AI Finder Banner */}
      <section className="py-10">
        <div className="max-w-7xl mx-auto px-4">
          <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-sky-900 via-blue-900 to-indigo-900 p-8 sm:p-12">
            <div className="absolute top-0 right-0 w-80 h-80 bg-sky-500/10 rounded-full blur-3xl" />
            <div className="absolute bottom-0 left-0 w-60 h-60 bg-blue-500/10 rounded-full blur-3xl" />
            <div className="relative z-10 flex flex-col sm:flex-row items-start sm:items-center gap-6">
              <div className="w-16 h-16 rounded-2xl bg-sky-500/20 border border-sky-400/30 flex items-center justify-center shrink-0">
                <Bot className="w-8 h-8 text-sky-400" />
              </div>
              <div className="flex-1">
                <span className="text-sky-400 text-xs font-bold uppercase tracking-wider">AI-Powered</span>
                <h3 className="text-white text-2xl sm:text-3xl font-black mt-1 mb-2">
                  Not sure which laptop to get?
                </h3>
                <p className="text-slate-300 text-sm sm:text-base leading-relaxed">
                  Our AI analyzes your purpose, budget, and preferences to recommend the perfect laptop for you.
                </p>
              </div>
              <Link
                href="/ai-finder"
                className="shrink-0 flex items-center gap-2 bg-sky-500 hover:bg-sky-400 text-white px-8 py-4 rounded-xl font-bold transition-all shadow-lg shadow-sky-900/50 hover:scale-105"
              >
                <Bot className="w-5 h-5" /> Try AI Finder
              </Link>
            </div>
          </div>
        </div>
      </section>

      {/* New Arrivals */}
      {newArrivals.length > 0 && (
        <section className="py-10 bg-white">
          <div className="max-w-7xl mx-auto px-4">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="w-1 h-8 bg-emerald-500 rounded-full" />
                <div>
                  <h2 className="text-2xl font-black text-slate-900">New Arrivals</h2>
                  <p className="text-slate-500 text-sm">Fresh additions to our store</p>
                </div>
              </div>
              <Link href="/products?isNew=true" className="flex items-center gap-1 text-sky-600 text-sm font-semibold">
                View All <ArrowRight className="w-4 h-4" />
              </Link>
            </div>
            <ProductGrid products={newArrivals} cols={4} />
          </div>
        </section>
      )}

      {/* Hot Deals */}
      {deals.length > 0 && (
        <section className="py-10 bg-slate-50">
          <div className="max-w-7xl mx-auto px-4">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                <div className="w-1 h-8 bg-red-500 rounded-full" />
                <h2 className="text-2xl font-black text-slate-900">Hot Deals</h2>
              </div>
              <Link href="/deals" className="flex items-center gap-1 text-sky-600 text-sm font-semibold">
                View All <ArrowRight className="w-4 h-4" />
              </Link>
            </div>
            <ProductGrid products={deals} cols={4} />
          </div>
        </section>
      )}

      {/* Brands */}
      <section className="py-10 bg-white border-y border-slate-100">
        <div className="max-w-7xl mx-auto px-4">
          <h2 className="text-center text-xs font-bold text-slate-400 uppercase tracking-widest mb-6">Authorized Reseller For</h2>
          <div className="flex flex-wrap items-center justify-center gap-6 sm:gap-10">
            {["Apple", "Dell", "HP", "Lenovo", "ASUS", "Microsoft", "Samsung", "Acer"].map((brand) => (
              <Link
                key={brand}
                href={`/laptops?brand=${brand.toLowerCase()}`}
                className="text-slate-400 hover:text-sky-600 text-lg font-black tracking-tight transition-colors"
              >
                {brand}
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* Testimonials */}
      <section className="py-10 bg-gradient-to-br from-sky-50 to-blue-50">
        <div className="max-w-7xl mx-auto px-4">
          <div className="text-center mb-8">
            <h2 className="text-2xl font-black text-slate-900 mb-2">What Our Customers Say</h2>
            <div className="flex items-center justify-center gap-2">
              <div className="flex">
                {[1,2,3,4,5].map((s) => <Star key={s} className="w-4 h-4 text-amber-400 fill-amber-400" />)}
              </div>
              <span className="text-slate-600 text-sm font-medium">4.9/5 from 500+ reviews</span>
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {[
              { name: "James Mwangi", role: "Software Engineer", comment: "Got my MacBook Pro in just 2 hours. Excellent service and the laptop was sealed in original box. ProTouch is my go-to store!", rating: 5 },
              { name: "Amina Hassan", role: "Student, UoN", comment: "Used the AI finder and it recommended the perfect laptop within my budget. Saved me hours of research. Highly recommend!", rating: 5 },
              { name: "Peter Odhiambo", role: "Freelance Designer", comment: "Best prices for iPhones in Nairobi. Got iPhone 15 Pro Max at a great deal. The 1-year warranty gives me peace of mind.", rating: 5 },
            ].map((review) => (
              <div key={review.name} className="bg-white rounded-2xl p-6 shadow-sm border border-sky-100">
                <div className="flex mb-3">
                  {[1,2,3,4,5].map((s) => (
                    <Star key={s} className={`w-4 h-4 ${s <= review.rating ? "text-amber-400 fill-amber-400" : "text-slate-200"}`} />
                  ))}
                </div>
                <p className="text-slate-600 text-sm leading-relaxed mb-4">&ldquo;{review.comment}&rdquo;</p>
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-sky-400 to-sky-600 flex items-center justify-center text-white font-bold text-sm">
                    {review.name.charAt(0)}
                  </div>
                  <div>
                    <p className="font-bold text-slate-800 text-sm">{review.name}</p>
                    <p className="text-slate-500 text-xs">{review.role}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Newsletter */}
      <section className="py-12 bg-gradient-to-r from-sky-700 to-blue-700 text-white">
        <div className="max-w-2xl mx-auto px-4 text-center">
          <TrendingUp className="w-10 h-10 mx-auto mb-4 text-sky-300" />
          <h2 className="text-2xl sm:text-3xl font-black mb-2">Stay Updated on Deals</h2>
          <p className="text-sky-200 mb-6 text-sm">Get exclusive offers, new arrivals, and tech news to your inbox.</p>
          <form className="flex gap-2 max-w-md mx-auto">
            <input
              type="email"
              placeholder="Enter your email address"
              className="flex-1 px-4 py-3 rounded-xl text-slate-800 text-sm focus:outline-none"
            />
            <button type="submit" className="bg-white text-sky-700 font-bold px-6 py-3 rounded-xl hover:bg-sky-50 transition-colors text-sm shrink-0">
              Subscribe
            </button>
          </form>
          <p className="text-sky-300 text-xs mt-3">No spam. Unsubscribe anytime.</p>
        </div>
      </section>
    </main>
  );
}
