import { useState, useEffect, useRef } from 'react';
import { ShoppingCart, Eye, Star, Check } from 'lucide-react';
import { useFBOContent } from '../../context/FBOContentContext';
import { toast } from 'sonner';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

interface FBOCatalogProps {
  onProductClick: (productId: string) => void;
}

export default function FBOCatalog({ onProductClick }: FBOCatalogProps) {
  const { content, getProductsByCategory, addToCart, getFeaturedProducts } = useFBOContent();
  const [activeCategory, setActiveCategory] = useState('all');
  const sectionRef = useRef<HTMLDivElement>(null);
  const gridRef = useRef<HTMLDivElement>(null);

  const products = activeCategory === 'featured' 
    ? getFeaturedProducts() 
    : getProductsByCategory(activeCategory);

  useEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from(gridRef.current, {
        scrollTrigger: {
          trigger: sectionRef.current,
          start: 'top 80%',
          toggleActions: 'play none none reverse',
        },
        y: 50,
        opacity: 0,
        duration: 0.6,
        ease: 'power3.out',
      });
    }, sectionRef);

    return () => ctx.revert();
  }, []);

  const handleAddToCart = (product: any, e: React.MouseEvent) => {
    e.stopPropagation();
    addToCart(product);
    toast.success(`${product.name} ajouté au panier`, {
      description: `${product.price.toFixed(2)} €`,
      icon: <Check className="w-4 h-4" />,
    });
  };

  return (
    <section
      id="catalog"
      ref={sectionRef}
      className="py-20 lg:py-32"
    >
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-[#e8f5e9] rounded-full mb-6">
            <ShoppingCart className="w-4 h-4 text-[#4caf50]" />
            <span className="text-sm font-medium text-[#2d7d32]">Notre catalogue</span>
          </div>
          <h2 className="text-3xl sm:text-4xl lg:text-5xl font-bold text-[#1b5e20] mb-4">
            Découvrez nos produits
          </h2>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            Une gamme complète de produits naturels à base d'Aloe Vera pour votre bien-être quotidien
          </p>
        </div>

        {/* Category Filter */}
        <div className="flex flex-wrap justify-center gap-3 mb-12">
          <button
            onClick={() => setActiveCategory('featured')}
            className={`px-5 py-2.5 rounded-full font-medium text-sm transition-all ${
              activeCategory === 'featured'
                ? 'bg-gradient-to-r from-[#2d7d32] to-[#4caf50] text-white shadow-lg'
                : 'bg-white text-gray-700 hover:bg-[#e8f5e9] shadow-sm'
            }`}
          >
            <span className="flex items-center gap-2">
              <Star className="w-4 h-4" />
              En vedette
            </span>
          </button>
          {content.categories.map((category) => (
            <button
              key={category.id}
              onClick={() => setActiveCategory(category.id)}
              className={`px-5 py-2.5 rounded-full font-medium text-sm transition-all ${
                activeCategory === category.id
                  ? 'bg-gradient-to-r from-[#2d7d32] to-[#4caf50] text-white shadow-lg'
                  : 'bg-white text-gray-700 hover:bg-[#e8f5e9] shadow-sm'
              }`}
            >
              {category.name}
            </button>
          ))}
        </div>

        {/* Products Grid */}
        <div
          ref={gridRef}
          className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
        >
          {products.map((product) => (
            <div
              key={product.id}
              onClick={() => onProductClick(product.id)}
              className="group bg-white rounded-2xl shadow-sm hover:shadow-xl transition-all duration-300 overflow-hidden cursor-pointer hover:-translate-y-1"
            >
              {/* Image */}
              <div className="relative aspect-square bg-gradient-to-br from-[#e8f5e9] to-[#c8e6c9] overflow-hidden">
                {/* Placeholder image */}
                <div className="absolute inset-0 flex items-center justify-center">
                  <div className="w-24 h-24 rounded-full bg-white/50 flex items-center justify-center">
                    <span className="text-4xl">🌿</span>
                  </div>
                </div>
                
                {/* Featured badge */}
                {product.featured && (
                  <div className="absolute top-3 left-3 px-3 py-1 bg-gradient-to-r from-[#ff9800] to-[#ffc107] text-white text-xs font-bold rounded-full shadow-md">
                    Vedette
                  </div>
                )}

                {/* Quick actions */}
                <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      onProductClick(product.id);
                    }}
                    className="w-12 h-12 bg-white rounded-full flex items-center justify-center hover:bg-[#e8f5e9] transition-colors shadow-lg"
                  >
                    <Eye className="w-5 h-5 text-[#1b5e20]" />
                  </button>
                </div>
              </div>

              {/* Content */}
              <div className="p-5">
                {/* Reference */}
                <div className="text-xs text-gray-400 mb-2">
                  Réf: {product.reference}
                </div>

                {/* Name */}
                <h3 className="font-bold text-[#1b5e20] mb-2 line-clamp-2 group-hover:text-[#2d7d32] transition-colors">
                  {product.name}
                </h3>

                {/* Description */}
                <p className="text-sm text-gray-500 mb-4 line-clamp-2">
                  {product.description}
                </p>

                {/* Price & CTA */}
                <div className="flex items-center justify-between">
                  <div>
                    <span className="text-2xl font-bold text-[#2d7d32]">
                      {product.price.toFixed(2)} €
                    </span>
                  </div>
                  <button
                    onClick={(e) => handleAddToCart(product, e)}
                    className="w-10 h-10 bg-gradient-to-r from-[#2d7d32] to-[#4caf50] rounded-full flex items-center justify-center hover:shadow-lg hover:scale-105 transition-all"
                  >
                    <ShoppingCart className="w-5 h-5 text-white" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Empty state */}
        {products.length === 0 && (
          <div className="text-center py-16">
            <div className="w-20 h-20 mx-auto mb-4 rounded-full bg-[#e8f5e9] flex items-center justify-center">
              <ShoppingCart className="w-10 h-10 text-[#4caf50]" />
            </div>
            <h3 className="text-xl font-semibold text-gray-700 mb-2">
              Aucun produit dans cette catégorie
            </h3>
            <p className="text-gray-500">
              Sélectionnez une autre catégorie pour voir nos produits
            </p>
          </div>
        )}
      </div>
    </section>
  );
}
