import { useState, useEffect, useRef } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ShoppingCart, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useFBOAdmin } from '@/context/FBOAdminContext';
import { usePriceFormatter } from '@/context/CurrencyContext';
import type { ProductCategory } from '@/types';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

interface FBOProductsProps {
  showAll?: boolean;
}

const categories: { id: ProductCategory | 'all'; label: string }[] = [
  { id: 'all', label: 'all' },
  { id: 'aloe-vera', label: 'aloe-vera' },
  { id: 'nutrition', label: 'nutrition' },
  { id: 'beauty', label: 'beauty' },
  { id: 'personal-care', label: 'personal-care' },
  { id: 'weight-management', label: 'weight-management' },
  { id: 'packs', label: 'packs' }
];

export default function FBOProducts({ showAll = false }: FBOProductsProps) {
  const { t, i18n } = useTranslation();
  const { products, addToCart, getFeaturedProducts, theme } = useFBOAdmin();
  const formatPrice = usePriceFormatter();
  const [selectedCategory, setSelectedCategory] = useState<ProductCategory | 'all'>('all');
  const sectionRef = useRef<HTMLElement>(null);
  const productsRef = useRef<HTMLDivElement>(null);

  const displayProducts = showAll 
    ? (selectedCategory === 'all' ? products : products.filter(p => p.category === selectedCategory))
    : getFeaturedProducts();

  useEffect(() => {
    if (showAll) {
      const ctx = gsap.context(() => {
        gsap.fromTo(productsRef.current?.children || [],
          { opacity: 0, y: 30 },
          {
            opacity: 1,
            y: 0,
            duration: 0.5,
            stagger: 0.1,
            ease: 'power3.out',
            scrollTrigger: {
              trigger: sectionRef.current,
              start: 'top 70%',
              toggleActions: 'play none none reverse'
            }
          }
        );
      }, sectionRef);

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

  const handleAddToCart = (product: typeof products[0]) => {
    addToCart(product);
  };

  return (
    <section
      ref={sectionRef}
      className="py-16 md:py-24"
      style={{ backgroundColor: theme.backgroundColor }}
    >
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="text-center max-w-2xl mx-auto mb-12">
          <h2 
            className="text-3xl sm:text-4xl font-bold mb-4"
            style={{ color: theme.textColor }}
          >
            {showAll ? t('fbo.categories.all') : 'Nos Produits Vedettes'}
          </h2>
          <p 
            className="text-lg"
            style={{ color: `${theme.textColor}99` }}
          >
            {showAll 
              ? 'Découvrez notre gamme complète de produits Forever Living'
              : 'Les produits les plus populaires de notre catalogue'
            }
          </p>
        </div>

        {/* Category Filter */}
        {showAll && (
          <Tabs 
            value={selectedCategory} 
            onValueChange={(v) => setSelectedCategory(v as ProductCategory | 'all')}
            className="mb-8"
          >
            <TabsList className="flex flex-wrap justify-center gap-2 bg-transparent">
              {categories.map((cat) => (
                <TabsTrigger
                  key={cat.id}
                  value={cat.id}
                  className="px-4 py-2 rounded-full text-sm font-medium transition-all data-[state=active]:text-white"
                  style={{
                    backgroundColor: selectedCategory === cat.id ? theme.primaryColor : `${theme.primaryColor}15`,
                    color: selectedCategory === cat.id ? 'white' : theme.primaryColor
                  }}
                >
                  {t(`fbo.categories.${cat.label}`)}
                </TabsTrigger>
              ))}
            </TabsList>
          </Tabs>
        )}

        {/* Products Grid */}
        <div 
          ref={productsRef}
          className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
        >
          {displayProducts.map((product) => (
            <div
              key={product.id}
              className="group rounded-2xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300"
              style={{ backgroundColor: theme.cardBackground }}
            >
              {/* Image */}
              <Link to={`/fbo/product/${product.id}`} className="block relative aspect-square overflow-hidden">
                <img
                  src={product.image}
                  alt={i18n.language === 'fr' ? product.name : product.nameEn}
                  className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                />
                {product.featured && (
                  <Badge 
                    className="absolute top-3 left-3 text-white"
                    style={{ backgroundColor: theme.accentColor }}
                  >
                    Vedette
                  </Badge>
                )}
                {!product.inStock && (
                  <div className="absolute inset-0 bg-black/50 flex items-center justify-center">
                    <span className="text-white font-medium">{t('fbo.outOfStock')}</span>
                  </div>
                )}
              </Link>

              {/* Content */}
              <div className="p-4">
                <span 
                  className="text-xs font-medium uppercase tracking-wide"
                  style={{ color: theme.primaryColor }}
                >
                  {t(`fbo.categories.${product.category}`)}
                </span>
                
                <Link to={`/fbo/product/${product.id}`}>
                  <h3 
                    className="font-semibold text-lg mt-1 mb-2 group-hover:text-[#2D5A27] transition-colors"
                    style={{ color: theme.textColor }}
                  >
                    {i18n.language === 'fr' ? product.name : product.nameEn}
                  </h3>
                </Link>

                <p 
                  className="text-sm line-clamp-2 mb-4"
                  style={{ color: `${theme.textColor}80` }}
                >
                  {i18n.language === 'fr' ? product.description : product.descriptionEn}
                </p>

                <div className="flex items-center justify-between">
                  <span 
                    className="text-xl font-bold"
                    style={{ color: theme.primaryColor }}
                  >
                    {formatPrice(product.price)}
                  </span>
                  
                  <Button
                    size="sm"
                    disabled={!product.inStock}
                    onClick={() => handleAddToCart(product)}
                    style={{ 
                      backgroundColor: product.inStock ? theme.primaryColor : '#ccc',
                    }}
                    className="text-white"
                  >
                    <ShoppingCart className="w-4 h-4 mr-1" />
                    {t('fbo.addToCart')}
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* View All Button */}
        {!showAll && (
          <div className="text-center mt-12">
            <Link to="/fbo/products">
              <Button
                variant="outline"
                size="lg"
                className="group"
                style={{ 
                  borderColor: theme.primaryColor,
                  color: theme.primaryColor 
                }}
              >
                {t('fbo.categories.all')}
                <ChevronRight className="ml-2 w-4 h-4 group-hover:translate-x-1 transition-transform" />
              </Button>
            </Link>
          </div>
        )}
      </div>
    </section>
  );
}
