import React, { useEffect, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useProductStore } from '@/store/productStore';
import { useCartStore } from '@/store/cartStore';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { 
  ArrowLeft, 
  Minus, 
  Plus, 
  ShoppingCart, 
  Check, 
  Truck,
  ShieldCheck,
  RefreshCcw,
  AlertCircle
} from 'lucide-react';
import ProductCard from '@/components/ProductCard';
import ProductVariantSelector from '@/components/ProductVariantSelector';
import { trackViewContent, trackAddToCart } from '@/lib/facebookPixel';
import { supabase } from '@/lib/supabaseClient';
import { cn } from '@/lib/utils';

const ProductDetailPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { toast } = useToast();
  const { fetchProductById, products, fetchProducts, fetchProductVariants } = useProductStore();
  const { addItem } = useCartStore();
  
  const [product, setProduct] = useState(null);
  const [variants, setVariants] = useState([]);
  const [selectedVariant, setSelectedVariant] = useState(null);
  const [quantity, setQuantity] = useState(1);
  const [relatedProducts, setRelatedProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // Gallery State
  const [galleryImages, setGalleryImages] = useState([]);
  const [activeImage, setActiveImage] = useState(null);

  useEffect(() => {
    let mounted = true;

    const loadData = async () => {
      if (!id) return;
      
      setLoading(true);
      try {
        const data = await fetchProductById(id);
        
        if (mounted && data) {
          setProduct(data);
          setActiveImage(data.image_url); // Default to main image
          trackViewContent(data);

          // Fetch Variants
          const variantData = await fetchProductVariants(id);
          setVariants(variantData || []);
          setSelectedVariant(null); // Reset selection on product change

          // Fetch additional images from gallery
          const { data: images } = await supabase
            .from('product_images')
            .select('*')
            .eq('product_id', id)
            .order('display_order', { ascending: true });
          
          if (images) {
            setGalleryImages(images);
          }

          // Fetch related products (lazy load if empty)
          if (data.category_id && products.length === 0) {
             fetchProducts({ categoryId: data.category_id, itemsPerPage: 4 });
          }
        }
      } catch (err) {
        console.error("Failed to load product details", err);
      } finally {
        if (mounted) setLoading(false);
      }
    };
    
    loadData();
    window.scrollTo(0, 0);

    return () => { mounted = false; };
  }, [id]);

  // Derived state for related products
  useEffect(() => {
     if (product && products.length > 0) {
        const related = products
           .filter(p => p.category_id === product.category_id && p.id !== product.id)
           .slice(0, 4);
        setRelatedProducts(related);
     }
  }, [product, products]);

  // Pricing Logic (Variant vs Base)
  const getDisplayPrice = () => {
     if (selectedVariant) return selectedVariant.price;
     return product?.price || 0;
  };

  const getDiscountPrice = () => {
     if (selectedVariant) return selectedVariant.discount_price;
     return product?.discount_price;
  };

  const currentPrice = getDisplayPrice();
  const discountPrice = getDiscountPrice();
  const hasDiscount = discountPrice && discountPrice < currentPrice;
  const discountPercentage = hasDiscount 
      ? ((currentPrice - discountPrice) / currentPrice * 100).toFixed(0) 
      : 0;

  const handleBuyNow = () => {
    if (!product) return;
    
    // Validation: If variants exist, one MUST be selected
    if (variants.length > 0 && !selectedVariant) {
        toast({
            title: "পছন্দ করুন",
            description: "অনুগ্রহ করে একটি ভেরিয়েন্ট (যেমন: সাইজ বা কালার) সিলেক্ট করুন।",
            variant: "destructive"
        });
        return;
    }

    // Validation: Stock Check
    const stock = selectedVariant ? selectedVariant.stock : product.stock;
    if (stock < quantity) {
        toast({
            title: "স্টক নেই",
            description: "দুঃখিত, এই পরিমাণ পণ্য স্টকে নেই।",
            variant: "destructive"
        });
        return;
    }

    // Add quantity directly instead of loop
    addItem(product, selectedVariant);
    if(quantity > 1) {
        for(let i=1; i < quantity; i++) {
             addItem(product, selectedVariant);
        }
    }

    // Track AddToCart Pixel
    trackAddToCart(product, quantity);
    
    // Navigate directly to checkout
    navigate('/checkout');
  };

  const incrementQty = () => setQuantity(q => q + 1);
  const decrementQty = () => setQuantity(q => q > 1 ? q - 1 : 1);

  if (loading) {
     return (
        <div className="container mx-auto px-4 py-10">
           <div className="grid grid-cols-1 lg:grid-cols-2 gap-10">
              <Skeleton className="aspect-square w-full rounded-2xl" />
              <div className="space-y-4">
                 <Skeleton className="h-8 w-3/4" />
                 <Skeleton className="h-6 w-1/4" />
                 <Skeleton className="h-32 w-full" />
                 <Skeleton className="h-12 w-1/2" />
              </div>
           </div>
        </div>
     );
  }

  if (!product) {
     return (
       <div className="min-h-[60vh] flex flex-col items-center justify-center p-4 text-center">
         <h2 className="text-2xl font-bold text-slate-800 mb-2">পণ্যটি পাওয়া যায়নি</h2>
         <p className="text-slate-500 mb-6">দুঃখিত, আপনি যে পণ্যটি খুঁজছেন তা বর্তমানে অনুপলব্ধ।</p>
         <Button onClick={() => navigate('/products')}>
            <ArrowLeft className="mr-2 h-4 w-4" /> পণ্য তালিকায় ফিরে যান
         </Button>
       </div>
     );
  }

  // Combine main image with gallery images for the thumbnails
  const allImages = [
      { id: 'main', image_url: product.image_url },
      ...galleryImages
  ].filter(img => img.image_url); // Filter out empty

  return (
    <>
      <Helmet>
        <title>{product.name} | মিনি মার্ভেলস</title>
        <meta name="description" content={product.description || product.name} />
      </Helmet>

      <div className="bg-white min-h-screen py-8">
        <div className="container mx-auto px-4">
          
          <div className="mb-6">
             <Link to="/products" className="inline-flex items-center text-slate-500 hover:text-orange-600 transition-colors">
                <ArrowLeft className="w-4 h-4 mr-2" /> পণ্য তালিকা
             </Link>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 mb-20">
             
             {/* Product Gallery Section */}
             <div className="space-y-4">
                <div className="relative aspect-square bg-slate-100 rounded-2xl overflow-hidden border border-slate-100 group">
                    <img 
                        src={activeImage} 
                        alt={product.name} 
                        className="w-full h-full object-contain transition-transform duration-500 group-hover:scale-105"
                    />
                </div>
                
                {allImages.length > 1 && (
                    <div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
                        {allImages.map((img) => (
                            <button
                                key={img.id}
                                onClick={() => setActiveImage(img.image_url)}
                                className={cn(
                                    "relative w-20 h-20 flex-shrink-0 bg-slate-50 rounded-lg overflow-hidden border-2 transition-all",
                                    activeImage === img.image_url ? "border-orange-500 ring-2 ring-orange-100" : "border-transparent hover:border-slate-300"
                                )}
                            >
                                <img src={img.image_url} alt="" className="w-full h-full object-cover" />
                            </button>
                        ))}
                    </div>
                )}
             </div>

             <div>
                <div className="mb-2">
                   <span className="bg-orange-100 text-orange-700 px-3 py-1 rounded-full text-xs font-bold">
                      {product.category?.name || 'সাধারণ'}
                   </span>
                </div>
                
                <h1 className="text-3xl md:text-4xl font-bold text-slate-800 mb-4 leading-tight">
                   {product.name}
                </h1>

                <div className="flex items-end gap-3 mb-6">
                   {hasDiscount ? (
                      <>
                        <div className="text-3xl font-bold text-orange-600">৳{discountPrice}</div>
                        <div className="text-xl text-slate-400 line-through mb-1">৳{currentPrice}</div>
                        <div className="bg-red-100 text-red-600 px-2 py-1 rounded text-sm font-bold mb-1">
                           -{discountPercentage}% Off
                        </div>
                      </>
                   ) : (
                      <div className="text-3xl font-bold text-blue-600">৳{currentPrice}</div>
                   )}
                </div>

                {/* Variant Selector */}
                <ProductVariantSelector 
                   variants={variants} 
                   selectedVariant={selectedVariant} 
                   onSelect={setSelectedVariant} 
                />

                <div className="prose prose-slate max-w-none mb-8">
                   <p className="text-slate-600 text-lg leading-relaxed whitespace-pre-line">
                      {product.description}
                   </p>
                </div>

                <div className="flex items-center gap-2 mb-8 text-green-600 font-medium">
                   <Check className="w-5 h-5" /> 
                   <span>
                      স্টক এ আছে 
                      ({selectedVariant ? selectedVariant.stock : product.stock} টি)
                   </span>
                </div>

                <div className="flex flex-col sm:flex-row gap-4 mb-10 pb-10 border-b border-slate-100">
                   <div className="flex items-center border border-slate-200 rounded-xl bg-slate-50 w-fit">
                      <button 
                         onClick={decrementQty}
                         className="p-4 hover:bg-slate-200 rounded-l-xl transition-colors text-slate-600"
                      >
                         <Minus className="w-5 h-5" />
                      </button>
                      <span className="w-16 text-center font-bold text-xl text-slate-800">{quantity}</span>
                      <button 
                         onClick={incrementQty}
                         className="p-4 hover:bg-slate-200 rounded-r-xl transition-colors text-slate-600"
                      >
                         <Plus className="w-5 h-5" />
                      </button>
                   </div>
                   
                   <Button 
                      onClick={handleBuyNow}
                      className="flex-1 bg-orange-600 hover:bg-orange-700 text-white font-bold h-14 text-lg rounded-xl shadow-lg shadow-orange-200"
                   >
                      <ShoppingCart className="w-5 h-5 mr-2" /> অর্ডার করুন
                   </Button>
                </div>
                
                {variants.length > 0 && !selectedVariant && (
                   <div className="flex items-center gap-2 text-amber-600 bg-amber-50 p-3 rounded-lg mb-6">
                      <AlertCircle className="w-5 h-5" />
                      <span className="text-sm font-medium">অর্ডার করার আগে একটি অপশন সিলেক্ট করুন</span>
                   </div>
                )}

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                   <div className="flex items-start gap-3">
                      <div className="bg-blue-50 p-2 rounded-lg text-blue-600"><Truck className="w-5 h-5" /></div>
                      <div>
                         <h4 className="font-bold text-slate-800 text-sm">দ্রুত ডেলিভারি</h4>
                         <p className="text-xs text-slate-500">২-৩ দিনের মধ্যে</p>
                      </div>
                   </div>
                   <div className="flex items-start gap-3">
                      <div className="bg-green-50 p-2 rounded-lg text-green-600"><ShieldCheck className="w-5 h-5" /></div>
                      <div>
                         <h4 className="font-bold text-slate-800 text-sm">জেনুইন পণ্য</h4>
                         <p className="text-xs text-slate-500">১০০% আসল</p>
                      </div>
                   </div>
                   <div className="flex items-start gap-3">
                      <div className="bg-purple-50 p-2 rounded-lg text-purple-600"><RefreshCcw className="w-5 h-5" /></div>
                      <div>
                         <h4 className="font-bold text-slate-800 text-sm">সহজ রিটার্ন</h4>
                         <p className="text-xs text-slate-500">৭ দিনের মধ্যে</p>
                      </div>
                   </div>
                </div>
             </div>
          </div>

          {relatedProducts.length > 0 && (
             <div className="mt-20">
                <h2 className="text-2xl font-bold text-slate-800 mb-8">সংশ্লিষ্ট অন্যান্য পণ্য</h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                   {relatedProducts.map(prod => (
                      <ProductCard key={prod.id} product={prod} />
                   ))}
                </div>
             </div>
          )}

        </div>
      </div>
    </>
  );
};

export default ProductDetailPage;