'use client';

import Image from 'next/image';
import { useState, useEffect } from 'react';
import { Drawer } from 'vaul';
import { type CarouselApi } from "@/components/ui/carousel";
import { Carousel, CarouselContent, CarouselItem } from "@/components/ui/carousel";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Button } from '@/components/ui/button';
import { ExternalLink, Package, Truck, Shield, Star, ChevronRight, Store, Tag } from 'lucide-react';
import { fetchProduct, getProductImages, getProductPricing, getProductVariants, getProductCategories, getProductClusters, getStockStatus, getProductGender, getProductSeason, getProductOccasion, type Product } from '@/lib/product-api';

interface ShoeResultsPopupProps {
  isOpen: boolean;
  onOpenChange: (isOpen: boolean) => void;
}

export default function ShoeResultsPopup({ isOpen, onOpenChange }: ShoeResultsPopupProps) {
  const [api, setApi] = useState<CarouselApi>();
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(false);
  const [activeImageUrl, setActiveImageUrl] = useState<string>('');
  const [selectedVariant, setSelectedVariant] = useState<string>('');
  const [selectedSize, setSelectedSize] = useState<string>('');

  // Fetch product data when popup opens
  useEffect(() => {
    if (isOpen && !product) {
      setLoading(true);
      fetchProduct().then((data) => {
        if (data) {
          setProduct(data);
          const images = getProductImages(data);
          if (images.length > 0) {
            setActiveImageUrl(images[0]);
          }
          // Set first available variant
          const variants = getProductVariants(data);
          if (variants.length > 0) {
            setSelectedVariant(variants[0].itemId);
            if (variants[0].sizes.length > 0) {
              setSelectedSize(variants[0].sizes[0]);
            }
          }
        }
        setLoading(false);
      });
    }
  }, [isOpen, product]);

  // Handle carousel selection
  useEffect(() => {
    if (!api || !product) return;

    const handleSelect = () => {
      const selectedIndex = api.selectedScrollSnap();
      const images = getProductImages(product);
      setActiveImageUrl(images[selectedIndex]);
    };

    api.on("select", handleSelect);
    return () => {
      api.off("select", handleSelect);
    };
  }, [api, product]);

  const handleThumbnailClick = (imageUrl: string) => {
    if (!product) return;
    const images = getProductImages(product);
    const index = images.findIndex(url => url === imageUrl);
    if (index !== -1) {
      api?.scrollTo(index);
    }
  };

  const handleViewDetails = () => {
    if (product?.linkText) {
      window.open(`https://www.impuls.com.mx/${product.linkText}/p`, '_blank');
    }
  };

  if (loading) {
    return (
      <Drawer.Root open={isOpen} onOpenChange={onOpenChange}>
        <Drawer.Portal>
          <Drawer.Overlay className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100]" />
          <Drawer.Content className="fixed bottom-0 left-0 right-0 mt-24 flex h-[90%] flex-col rounded-t-3xl bg-black/90 backdrop-blur-xl border-t-2 border-white/20 z-[101] shadow-2xl">
            <Drawer.Title className="sr-only">Cargando producto</Drawer.Title>
            <Drawer.Description className="sr-only">Obteniendo información del producto</Drawer.Description>
            <div className="flex-1 flex items-center justify-center">
              <div className="flex flex-col items-center gap-4">
                <div className="w-12 h-12 border-4 border-blue-400 border-t-transparent rounded-full animate-spin"></div>
                <p className="text-white/80 text-lg">Cargando producto...</p>
              </div>
            </div>
          </Drawer.Content>
        </Drawer.Portal>
      </Drawer.Root>
    );
  }

  if (!product) return null;

  const images = getProductImages(product);
  const pricing = getProductPricing(product);
  const variants = getProductVariants(product);
  const categories = getProductCategories(product);
  const clusters = getProductClusters(product);
  const genderInfo = getProductGender(product);
  const seasonInfo = getProductSeason(product);
  const occasionInfo = getProductOccasion(product);
  const selectedVariantData = variants.find(v => v.itemId === selectedVariant);

  return (
    <Drawer.Root open={isOpen} onOpenChange={onOpenChange}>
      <Drawer.Portal>
        <Drawer.Overlay className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100]" />
        <Drawer.Content className="fixed bottom-0 left-0 right-0 mt-24 flex h-[90%] flex-col rounded-t-3xl bg-black/90 backdrop-blur-xl border-t-2 border-white/20 z-[101] shadow-2xl">
          <div className="flex-1 overflow-y-auto rounded-t-[24px]">
            <div className="sticky top-0 z-10 w-full bg-black/80 backdrop-blur-xl rounded-t-[24px] py-6 border-b border-white/10">
              <div className="mx-auto h-1.5 w-16 flex-shrink-0 rounded-full bg-white/40 shadow-lg" />
            </div>
            <Drawer.Title className="sr-only">{product.productName}</Drawer.Title>
            <Drawer.Description className="sr-only">{product.description}</Drawer.Description>

            <div className="p-6 space-y-6">
              {/* Category Breadcrumb */}
              {(categories.length > 0 || genderInfo) && (
                <div className="flex items-center gap-2 text-sm text-white/60">
                  {/* Gender first if available */}
                  {genderInfo && (
                    <>
                      <span className="flex items-center gap-1 hover:text-white/80 cursor-pointer transition-colors">
                        <span>{genderInfo.icon}</span>
                        {genderInfo.label}
                      </span>
                      {categories.length > 0 && <ChevronRight size={12} />}
                    </>
                  )}
                  
                  {/* Then categories */}
                  {categories.map((category, index) => (
                    <div key={index} className="flex items-center gap-2">
                      <span className="hover:text-white/80 cursor-pointer transition-colors">
                        {category}
                      </span>
                      {index < categories.length - 1 && <ChevronRight size={12} />}
                    </div>
                  ))}
                </div>
              )}

              {/* Brand Badge and Tags */}
              <div className="space-y-3">
                <div className="flex items-center flex-wrap gap-2">
                  <Badge variant="secondary" className="bg-white/10 text-white border-white/20">
                    <Store size={12} className="mr-1" />
                    {product.brand}
                  </Badge>
                  {pricing.discount > 0 && (
                    <Badge className="bg-red-500/20 text-red-300 border-red-500/30">
                      -{pricing.discount}%
                    </Badge>
                  )}
                </div>
                
                {/* Gender, Season & Occasion Info */}
                <div className="flex items-center flex-wrap gap-2">
                  {genderInfo && (
                    <Badge variant="outline" className={genderInfo.color}>
                      <span className="mr-1">{genderInfo.icon}</span>
                      {genderInfo.label}
                    </Badge>
                  )}
                  {seasonInfo && (
                    <Badge variant="outline" className={seasonInfo.color}>
                      <span className="mr-1">{seasonInfo.icon}</span>
                      {seasonInfo.season}
                    </Badge>
                  )}
                  {occasionInfo && (
                    <Badge variant="outline" className={occasionInfo.color}>
                      <span className="mr-1">{occasionInfo.icon}</span>
                      {occasionInfo.label}
                    </Badge>
                  )}
                </div>
                
                {/* Product Clusters/Tags */}
                {clusters.length > 0 && (
                  <div className="flex items-center flex-wrap gap-2">
                    {clusters.map((cluster) => (
                      <Badge 
                        key={cluster.id} 
                        variant="outline" 
                        className="bg-blue-500/10 text-blue-300 border-blue-500/30 text-xs"
                      >
                        <Tag size={10} className="mr-1" />
                        {cluster.displayName}
                      </Badge>
                    ))}
                  </div>
                )}
              </div>

              {/* Product Name & Price */}
              <div className="space-y-2">
                <h1 className="text-2xl font-bold tracking-tight text-white md:text-3xl leading-tight">
                  {product.productName}
                </h1>
                <div className="flex items-baseline gap-4">
                  <p className="text-3xl font-bold bg-gradient-to-r from-green-400 to-emerald-400 bg-clip-text text-transparent">
                    ${pricing.price.toFixed(2)}
                  </p>
                  {pricing.listPrice > pricing.price && (
                    <p className="text-xl text-gray-500 line-through">
                      ${pricing.listPrice.toFixed(2)}
                    </p>
                  )}
                </div>
              </div>

              {/* Image Carousel */}
              <div className="bg-white/5 backdrop-blur-sm rounded-2xl p-4 border border-white/10">
                {images.length > 0 ? (
                  <Carousel setApi={setApi} className="w-full">
                    <CarouselContent>
                      {images.map((url, index) => (
                        <CarouselItem key={index}>
                          <div className="relative h-72 w-full overflow-hidden rounded-xl bg-white/10 backdrop-blur-sm border border-white/20 md:h-80">
                            <Image 
                              src={url} 
                              alt={`${product.productName} imagen ${index + 1}`} 
                              layout="fill" 
                              objectFit="contain"
                              className="p-4"
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                              }}
                            />
                          </div>
                        </CarouselItem>
                      ))}
                    </CarouselContent>
                  </Carousel>
                ) : (
                  <div className="relative h-72 w-full overflow-hidden rounded-xl bg-white/10 backdrop-blur-sm border border-white/20 md:h-80 flex items-center justify-center">
                    <div className="flex flex-col items-center gap-4 text-white/60">
                      <Package size={48} />
                      <p className="text-lg font-medium">Imagen no disponible</p>
                    </div>
                  </div>
                )}
              </div>

              {/* Size Selection with Stock Info */}
              {variants.length > 0 && (
                <div className="bg-white/5 backdrop-blur-sm rounded-2xl p-6 border border-white/10">
                  <h3 className="text-xl font-bold text-white mb-4 flex items-center gap-3">
                    <div className="w-2 h-2 bg-blue-400 rounded-full"></div>
                    Tallas y Disponibilidad
                  </h3>
                  <div className="space-y-3">
                    {variants.map((variant) => {
                      const stockInfo = getStockStatus(variant.availableQuantity);
                      const isOutOfStock = stockInfo.status === 'out_of_stock';
                      
                      return variant.sizes.map((size) => {
                        const isSelected = selectedSize === size && selectedVariant === variant.itemId;
                        
                        return (
                          <div 
                            key={`${variant.itemId}-${size}`}
                            className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10"
                          >
                            <button
                              onClick={() => {
                                if (!isOutOfStock) {
                                  setSelectedSize(size);
                                  setSelectedVariant(variant.itemId);
                                }
                              }}
                              disabled={isOutOfStock}
                              className={`flex-1 text-left font-medium transition-colors ${
                                isSelected 
                                  ? 'text-blue-400' 
                                  : isOutOfStock 
                                    ? 'text-gray-500 cursor-not-allowed' 
                                    : 'text-white hover:text-blue-400'
                              }`}
                            >
                              Talla {size}
                            </button>
                            
                            <div className="flex items-center gap-2">
                              {variant.price > 0 && (
                                <span className="text-sm text-white/60">
                                  ${variant.price.toFixed(2)}
                                </span>
                              )}
                              <Badge 
                                variant={isOutOfStock ? "secondary" : "default"}
                                className={`text-xs ${
                                  stockInfo.status === 'out_of_stock' 
                                    ? 'bg-red-500/20 text-red-300 border-red-500/30'
                                    : stockInfo.status === 'low_stock'
                                    ? 'bg-yellow-500/20 text-yellow-300 border-yellow-500/30'
                                    : stockInfo.status === 'limited'
                                    ? 'bg-orange-500/20 text-orange-300 border-orange-500/30'
                                    : 'bg-green-500/20 text-green-300 border-green-500/30'
                                }`}
                              >
                                {stockInfo.label}
                              </Badge>
                            </div>
                            
                            {isSelected && (
                              <div className="ml-2 w-2 h-2 bg-blue-400 rounded-full"></div>
                            )}
                          </div>
                        );
                      });
                    })}
                  </div>
                </div>
              )}

              {/* Product Details Accordion */}
              <div className="bg-white/5 backdrop-blur-sm rounded-2xl border border-white/10 overflow-hidden">
                <Accordion type="single" collapsible className="w-full">
                  <AccordionItem value="description" className="border-white/10">
                    <AccordionTrigger className="px-6 py-4 text-white hover:no-underline hover:bg-white/5">
                      <div className="flex items-center gap-3">
                        <Star className="w-4 h-4" />
                        <span className="font-semibold">Descripción</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent className="px-6 pb-4 text-white/80 leading-relaxed">
                      {product.description || 'Descripción no disponible.'}
                    </AccordionContent>
                  </AccordionItem>
                  
                  <AccordionItem value="variants" className="border-white/10">
                    <AccordionTrigger className="px-6 py-4 text-white hover:no-underline hover:bg-white/5">
                      <div className="flex items-center gap-3">
                        <Package className="w-4 h-4" />
                        <span className="font-semibold">Variantes ({variants.length})</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent className="px-6 pb-4">
                      <div className="space-y-3">
                        {variants.map((variant) => (
                          <div key={variant.itemId} className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10">
                            <div className="text-white font-medium">{variant.name}</div>
                            <Badge variant={variant.isAvailable ? "default" : "secondary"}>
                              {variant.isAvailable ? 'Disponible' : 'Agotado'}
                            </Badge>
                          </div>
                        ))}
                      </div>
                    </AccordionContent>
                  </AccordionItem>
                  
                  <AccordionItem value="shipping" className="border-white/10">
                    <AccordionTrigger className="px-6 py-4 text-white hover:no-underline hover:bg-white/5">
                      <div className="flex items-center gap-3">
                        <Truck className="w-4 h-4" />
                        <span className="font-semibold">Envío y Devoluciones</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent className="px-6 pb-4 text-white/80">
                      <div className="space-y-2">
                        <p>• Envío gratuito en compras mayores a $999</p>
                        <p>• Entrega en 3-5 días hábiles</p>
                        <p>• Devoluciones gratuitas dentro de 30 días</p>
                      </div>
                    </AccordionContent>
                  </AccordionItem>
                  
                  <AccordionItem value="seller" className="border-white/10">
                    <AccordionTrigger className="px-6 py-4 text-white hover:no-underline hover:bg-white/5">
                      <div className="flex items-center gap-3">
                        <Store className="w-4 h-4" />
                        <span className="font-semibold">Vendedor</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent className="px-6 pb-4 text-white/80">
                      {selectedVariantData && selectedVariantData.seller && (
                        <div className="space-y-3">
                          <div className="flex items-center justify-between">
                            <span>Vendedor:</span>
                            <span className="font-medium text-white">{selectedVariantData.seller.sellerName}</span>
                          </div>
                          <div className="flex items-center justify-between">
                            <span>Stock disponible:</span>
                            <span className={getStockStatus(selectedVariantData.availableQuantity).color}>
                              {getStockStatus(selectedVariantData.availableQuantity).label}
                            </span>
                          </div>
                          {selectedVariantData.availableQuantity > 0 && (
                            <div className="text-sm text-white/60 mt-2">
                              • Envío directo del vendedor
                              • Procesamiento en 1-2 días hábiles
                            </div>
                          )}
                        </div>
                      )}
                    </AccordionContent>
                  </AccordionItem>
                  
                  <AccordionItem value="warranty" className="border-white/10 border-b-0">
                    <AccordionTrigger className="px-6 py-4 text-white hover:no-underline hover:bg-white/5">
                      <div className="flex items-center gap-3">
                        <Shield className="w-4 h-4" />
                        <span className="font-semibold">Garantía</span>
                      </div>
                    </AccordionTrigger>
                    <AccordionContent className="px-6 pb-4 text-white/80">
                      <div className="space-y-2">
                        <p>• Garantía del fabricante de 6 meses</p>
                        <p>• Protección contra defectos de manufactura</p>
                        <p>• Soporte técnico especializado</p>
                      </div>
                    </AccordionContent>
                  </AccordionItem>
                </Accordion>
              </div>
            </div>
          </div>
          
          {/* Action Button */}
          <div className="sticky bottom-0 w-full border-t border-white/10 bg-black/80 backdrop-blur-xl p-6">
            <div className="flex gap-3">
              <Button 
                size="lg" 
                onClick={handleViewDetails}
                className="flex-1 h-14 text-lg bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700 border-0 shadow-lg shadow-blue-500/25 transform hover:scale-[1.02] transition-all duration-200"
              >
                <ExternalLink className="w-5 h-5 mr-2" />
                Ver Detalles Completos
              </Button>
              <Button size="lg" variant="outline" className="h-14 px-6 bg-white/5 border-white/20 text-white hover:bg-white/10 hover:border-white/30">
                ❤️
              </Button>
            </div>
          </div>
        </Drawer.Content>
      </Drawer.Portal>
    </Drawer.Root>
  );
}