"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { ArrowRight, Truck, Shield, Sparkles, Award } from "lucide-react";
import { supabase } from "@/lib/supabase";
import { Product, HeroSlide, Collection, BlogPost } from "@/lib/types";
import { ProductCard } from "@/components/product-card";
import { BlogPostCard } from "@/components/blog-post-card";
import { NewsletterSection } from "@/components/newsletter-section";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from "@/components/ui/carousel";

export default function HomePage() {
  const [heroSlides, setHeroSlides] = useState<HeroSlide[]>([]);
  const [collections, setCollections] = useState<Collection[]>([]);
  const [popularProducts, setPopularProducts] = useState<Product[]>([]);
  const [saleProducts, setSaleProducts] = useState<Product[]>([]);
  const [newProducts, setNewProducts] = useState<Product[]>([]);
  const [latestPosts, setLatestPosts] = useState<BlogPost[]>([]);
  const [currentSlide, setCurrentSlide] = useState(0);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (heroSlides.length <= 1) return;
    const timer = setInterval(() => {
      setCurrentSlide((prev) => (prev + 1) % heroSlides.length);
    }, 6000);
    return () => clearInterval(timer);
  }, [heroSlides.length]);

  async function loadData() {
    const [heroRes, collRes, popRes, saleRes, newRes, postRes] = await Promise.all([
      supabase
        .from("hero_slides")
        .select("*")
        .eq("is_active", true)
        .order("display_order"),
      supabase
        .from("collections")
        .select("*")
        .eq("is_featured", true)
        .eq("is_active", true),
      supabase
        .from("products")
        .select("*, product_images(*)")
        .eq("is_active", true)
        .eq("is_bestseller", true)
        .limit(4),
      supabase
        .from("products")
        .select("*, product_images(*)")
        .eq("is_active", true)
        .not("compare_at_price", "is", null)
        .order("created_at", { ascending: false }),
      supabase
        .from("products")
        .select("*, product_images(*)")
        .eq("is_active", true)
        .order("created_at", { ascending: false })
        .limit(8),
      supabase
        .from("blog_posts")
        .select("*")
        .eq("is_published", true)
        .lte("published_at", new Date().toISOString())
        .order("published_at", { ascending: false })
        .limit(3),
    ]);

    if (heroRes.data) setHeroSlides(heroRes.data);
    if (collRes.data) setCollections(collRes.data);
    if (popRes.data) setPopularProducts(popRes.data);
    if (saleRes.data) {
      setSaleProducts(
        saleRes.data
          .filter((product) => product.compare_at_price !== null && product.compare_at_price > product.price)
          .slice(0, 4)
      );
    }
    if (newRes.data) setNewProducts(newRes.data);
    if (postRes.data) setLatestPosts(postRes.data);
  }

  const slide = heroSlides[currentSlide];

  return (
    <div>
      {/* Hero */}
      <section className="relative h-screen min-h-[600px] flex items-center">
        {heroSlides.map((s, i) => (
          <div
            key={s.id}
            className={`absolute inset-0 transition-opacity duration-1000 ${
              i === currentSlide ? "opacity-100" : "opacity-0"
            }`}
          >
            <Image
              src={s.image_url}
              alt=""
              fill
              priority={i === 0}
              sizes="100vw"
              className="object-cover"
            />
            <div className="absolute inset-0 bg-linear-to-r from-black/60 via-black/30 to-transparent" />
          </div>
        ))}
        {slide && (
          <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
            <div className="max-w-xl animate-fade-in-up">
              <h1 className="font-serif text-4xl md:text-5xl lg:text-6xl text-white font-semibold leading-tight mb-4">
                {slide.title}
              </h1>
              <p className="text-lg text-white/80 leading-relaxed mb-8">
                {slide.subtitle}
              </p>
              <div className="flex flex-wrap gap-4">
                {slide.button_text && (
                  <Link
                    href={slide.button_link}
                    className="px-8 py-3 gold-gradient text-white font-medium rounded hover:opacity-90 transition-opacity"
                  >
                    {slide.button_text}
                  </Link>
                )}
                {slide.button2_text && (
                  <Link
                    href={slide.button2_link}
                    className="px-8 py-3 border border-white/50 text-white font-medium rounded hover:bg-white/10 transition-colors"
                  >
                    {slide.button2_text}
                  </Link>
                )}
              </div>
            </div>
          </div>
        )}
        {heroSlides.length > 1 && (
          <div className="absolute bottom-8 left-1/2 -translate-x-1/2 flex gap-2 z-10">
            {heroSlides.map((_, i) => (
              <button
                key={i}
                onClick={() => setCurrentSlide(i)}
                className={`w-2 h-2 rounded-full transition-all ${
                  i === currentSlide ? "bg-brand-gold w-6" : "bg-white/50"
                }`}
              />
            ))}
          </div>
        )}
      </section>

      {/* Benefits */}
      <section className="py-12 bg-white border-b border-brand-sand/30">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-6 lg:gap-8">
            {[
              { icon: Truck, title: "Livraison Express", desc: "Offerte dès 150€" },
              { icon: Shield, title: "Paiement Securise", desc: "Stripe & Alma 3x" },
              { icon: Sparkles, title: "Opticienne agréée", desc: "Vos lunettes de vue sont remboursées par la Sécurité sociale et votre mutuelle" },
              { icon: Award, title: "Selection Premium", desc: "Qualite garantie" },
            ].map(({ icon: Icon, title, desc }) => (
              <div key={title} className="flex items-center gap-3 lg:gap-4">
                <div className="w-10 h-10 lg:w-12 lg:h-12 rounded-full bg-brand-cream flex items-center justify-center shrink-0">
                  <Icon size={20} className="text-brand-gold" />
                </div>
                <div>
                  <p className="text-sm font-semibold text-brand-black">{title}</p>
                  <p className="text-xs text-brand-charcoal/60">{desc}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Promotions */}
      {saleProducts.length > 0 && (
        <section className="py-20 bg-brand-cream/30">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-end justify-between mb-10">
              <div>
                <span className="text-brand-gold text-xs font-medium uppercase tracking-widest">
                  Offres du moment
                </span>
                <h2 className="font-serif text-3xl md:text-4xl text-brand-black mt-1 mb-2">
                  Nos Promotions
                </h2>
                <p className="text-brand-charcoal/70">
                  Découvrez nos montures à prix réduit
                </p>
              </div>
              <Link
                href="/boutique?promo=true"
                className="hidden md:flex items-center gap-1 text-sm font-medium text-brand-gold hover:gap-2 transition-all"
              >
                Voir les promotions <ArrowRight size={14} />
              </Link>
            </div>
            <ResponsiveProductList products={saleProducts} label="Produits en promotion" />
            <div className="mt-10 text-center md:hidden">
              <Link
                href="/boutique?promo=true"
                className="inline-flex items-center gap-2 px-6 py-2.5 border border-brand-gold text-brand-gold text-sm font-medium rounded hover:bg-brand-gold hover:text-white transition-colors"
              >
                Voir les promotions <ArrowRight size={14} />
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* Collections */}
      {collections.length > 0 && (
        <section className="py-20 bg-brand-cream/30">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="text-center mb-12">
              <h2 className="font-serif text-3xl md:text-4xl text-brand-black mb-3">
                Nos Collections
              </h2>
              <p className="text-brand-charcoal/70 max-w-md mx-auto">
                Des montures pensees pour chaque personnalite
              </p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {collections.map((col) => (
                <Link
                  key={col.id}
                  href={`/collections/${col.slug}`}
                  className="group relative aspect-4/5 rounded-lg overflow-hidden"
                >
                  <Image
                    src={col.image_url}
                    alt={col.name}
                    fill
                    sizes="(min-width: 768px) 33vw, 100vw"
                    className="object-cover transition-transform duration-700 group-hover:scale-105"
                  />
                  <div className="absolute inset-0 bg-linear-to-t from-black/60 via-transparent to-transparent" />
                  <div className="absolute bottom-0 left-0 right-0 p-6">
                    <h3 className="font-serif text-xl text-white mb-1">{col.name}</h3>
                    <p className="text-sm text-white/70">{col.description}</p>
                    <span className="inline-flex items-center gap-1 text-sm text-brand-gold mt-3 group-hover:gap-2 transition-all">
                      Decouvrir <ArrowRight size={14} />
                    </span>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Popular Products */}
      {popularProducts.length > 0 && (
        <section className="py-20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-end justify-between mb-10">
              <div>
                <h2 className="font-serif text-3xl md:text-4xl text-brand-black mb-2">
                  Les Plus Populaires
                </h2>
                <p className="text-brand-charcoal/70">
                  Nos best-sellers plebiscites par nos clientes
                </p>
              </div>
              <Link
                href="/boutique"
                className="hidden md:flex items-center gap-1 text-sm font-medium text-brand-gold hover:gap-2 transition-all"
              >
                Voir tout <ArrowRight size={14} />
              </Link>
            </div>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 lg:gap-6">
              {popularProducts.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Brand Story */}
      <section className="py-20 bg-brand-black">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="grid lg:grid-cols-2 gap-12 items-center">
            <div>
              <span className="text-brand-gold text-sm font-medium uppercase tracking-wider">
                Notre Histoire
              </span>
              <h2 className="font-serif text-3xl md:text-4xl text-white mt-3 mb-6">
                L&apos;elegance du regard, l&apos;art du detail
              </h2>
              <p className="text-brand-sand/80 leading-relaxed mb-4">
                L&apos;Uni-Verre de Jessica est nee d&apos;une passion pour
                l&apos;optique de luxe et le desir de rendre l&apos;elegance
                accessible a toutes.
              </p>
              <p className="text-brand-sand/80 leading-relaxed mb-8">
                Chaque monture est selectionnee avec soin pour sa qualite
                exceptionnelle, son design unique et son confort incomparable.
              </p>
              <Link
                href="/a-propos"
                className="inline-flex items-center gap-2 text-brand-gold font-medium hover:gap-3 transition-all"
              >
                En savoir plus <ArrowRight size={16} />
              </Link>
            </div>
            <div className="relative aspect-4/5 rounded-lg overflow-hidden">
              <Image
                src="https://images.pexels.com/photos/1493111/pexels-photo-1493111.jpeg?auto=compress&cs=tinysrgb&w=800"
                alt="Notre histoire"
                fill
                sizes="(min-width: 1024px) 50vw, 100vw"
                className="object-cover"
              />
            </div>
          </div>
        </div>
      </section>

      {/* New Products */}
      {newProducts.length > 0 && (
        <section className="py-20 bg-brand-cream/20">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-end justify-between mb-10">
              <div>
                <span className="text-brand-gold text-xs font-medium uppercase tracking-widest">
                  Derniers arrivages
                </span>
                <h2 className="font-serif text-3xl md:text-4xl text-brand-black mt-1 mb-2">
                  Nouveaux Modèles
                </h2>
                <p className="text-brand-charcoal/70">
                  Découvrez les dernières montures ajoutées à notre catalogue
                </p>
              </div>
              <Link
                href="/boutique"
                className="hidden md:flex items-center gap-1 text-sm font-medium text-brand-gold hover:gap-2 transition-all"
              >
                Voir tout <ArrowRight size={14} />
              </Link>
            </div>
            <ResponsiveProductList products={newProducts} label="Nouveaux modèles" />
            <div className="mt-10 text-center md:hidden">
              <Link
                href="/boutique"
                className="inline-flex items-center gap-2 px-6 py-2.5 border border-brand-gold text-brand-gold text-sm font-medium rounded hover:bg-brand-gold hover:text-white transition-colors"
              >
                Voir tous les modèles <ArrowRight size={14} />
              </Link>
            </div>
          </div>
        </section>
      )}

      {/* Latest Articles */}
      {latestPosts.length > 0 && (
        <section className="py-20">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
            <div className="mb-10 flex items-end justify-between">
              <div>
                <span className="text-xs font-medium uppercase tracking-widest text-brand-gold">
                  Conseils &amp; actualités
                </span>
                <h2 className="mt-1 mb-2 font-serif text-3xl text-brand-black md:text-4xl">
                  Nos derniers articles
                </h2>
                <p className="text-brand-charcoal/70">
                  Conseils d&apos;opticienne pour prendre soin de votre regard
                </p>
              </div>
              <Link
                href="/blog"
                className="hidden items-center gap-1 text-sm font-medium text-brand-gold transition-all hover:gap-2 md:flex"
              >
                Voir le blog <ArrowRight size={14} />
              </Link>
            </div>
            <div className="grid gap-6 md:grid-cols-3">
              {latestPosts.map((post) => (
                <BlogPostCard key={post.id} post={post} />
              ))}
            </div>
            <div className="mt-10 text-center md:hidden">
              <Link
                href="/blog"
                className="inline-flex min-h-11 items-center gap-2 rounded border border-brand-gold px-6 py-2.5 text-sm font-medium text-brand-gold transition-colors hover:bg-brand-gold hover:text-white"
              >
                Voir le blog <ArrowRight size={14} />
              </Link>
            </div>
          </div>
        </section>
      )}

      <NewsletterSection />
    </div>
  );
}

function ResponsiveProductList({ products, label }: { products: Product[]; label: string }) {
  return (
    <>
      <Carousel
        opts={{ align: "start" }}
        className="lg:hidden"
        aria-label={label}
      >
        <CarouselContent className="-ml-3">
          {products.map((product) => (
            <CarouselItem
              key={product.id}
              className="basis-[72%] pl-3 sm:basis-[45%] md:basis-[33.333%]"
            >
              <ProductCard product={product} />
            </CarouselItem>
          ))}
        </CarouselContent>
        <CarouselPrevious
          className="!left-2 !top-1/2 h-11 w-11 border-brand-sand bg-white/95 text-brand-charcoal shadow-sm hover:bg-white"
        />
        <CarouselNext
          className="!right-2 !top-1/2 h-11 w-11 border-brand-sand bg-white/95 text-brand-charcoal shadow-sm hover:bg-white"
        />
      </Carousel>
      <div className="hidden lg:grid lg:grid-cols-4 lg:gap-6">
        {products.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>
    </>
  );
}
