import { useState } from 'react';
import { Link } from 'react-router-dom';
import { X, ShoppingCart, Eye } from 'lucide-react';
import { cn } from '@/lib/utils';
import { getSectionBackground } from '@/lib/sectionStyles';
import { formatPrice } from '@/lib/currency';
import { useCartStore } from '@/lib/cart/store';
import { apiClient } from '@/lib/api/client';
import { toast } from 'sonner';

interface Hotspot {
  /** 0-100 percentage from left */
  x: number;
  /** 0-100 percentage from top */
  y: number;
  product_id: number;
  product_name?: string;
  product_slug?: string;
  product_price?: string;
  product_image?: string;
}

interface ShoppableImageProps {
  id: string;
  image?: string;
  alt?: string;
  title?: string;
  subtitle?: string;
  hotspots?: Hotspot[];
  styles?: Record<string, any>;
  elementStyles?: Record<string, any>;
}

// Demo hotspots shown when no data is configured
const DEMO_HOTSPOTS: Hotspot[] = [
  { x: 30, y: 40, product_id: 0, product_name: 'Sample Product A', product_price: '29.99', product_slug: 'sample-a' },
  { x: 65, y: 60, product_id: 0, product_name: 'Sample Product B', product_price: '49.99', product_slug: 'sample-b' },
];

export function ShoppableImage({
  id,
  image,
  alt = 'Shoppable image',
  title,
  subtitle,
  hotspots,
  styles,
  elementStyles,
}: ShoppableImageProps) {
  const sectionBg = getSectionBackground(styles);
  const [activeHotspot, setActiveHotspot] = useState<number | null>(null);
  const { addItem, openCart } = useCartStore();

  const displayHotspots = (hotspots && hotspots.length > 0) ? hotspots : DEMO_HOTSPOTS;
  const hasImage = !!image;

  const handleAddToCart = async (hotspot: Hotspot, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!hotspot.product_id) {
      toast.info('Configure this hotspot in the Admin panel');
      return;
    }
    try {
      await apiClient.post(apiClient.endpoints.cart.add, {
        product_id: hotspot.product_id,
        quantity: 1,
      });
      addItem({
        key: String(hotspot.product_id),
        product_id: hotspot.product_id,
        name: hotspot.product_name || 'Product',
        price: parseFloat(hotspot.product_price || '0'),
        quantity: 1,
        image: hotspot.product_image,
      });
      toast.success(`${hotspot.product_name} added to cart!`);
      openCart();
    } catch {
      toast.error('Failed to add to cart');
    }
  };

  return (
    <section id={id} className="wn-section wn-shoppable-image py-12 md:py-16" style={sectionBg.style}>
      <div className="container mx-auto px-4 max-w-7xl">
        {(title || subtitle) && (
          <div className="mb-8 text-center">
            {title && (
              <h2 className="text-3xl md:text-4xl font-bold" style={{ color: elementStyles?.title?.color }}>
                {title}
              </h2>
            )}
            {subtitle && (
              <p className="text-muted-foreground mt-2" style={{ color: elementStyles?.subtitle?.color }}>
                {subtitle}
              </p>
            )}
          </div>
        )}

        {/* Image + hotspot container */}
        <div className="relative inline-block w-full rounded-2xl overflow-hidden">
          {hasImage ? (
            <img src={image} alt={alt} className="w-full h-auto block" />
          ) : (
            /* Placeholder gradient when no image is set */
            <div className="w-full aspect-[16/9] bg-gradient-to-br from-violet-100 to-indigo-100 flex items-center justify-center">
              <div className="text-center text-muted-foreground">
                <Eye className="w-12 h-12 mx-auto mb-3 opacity-30" />
                <p className="text-sm">Set an image in the page editor to activate this section</p>
              </div>
            </div>
          )}

          {/* Hotspot pins */}
          {displayHotspots.map((hotspot, idx) => {
            const isActive = activeHotspot === idx;

            return (
              <div
                key={idx}
                className="absolute"
                style={{ left: `${hotspot.x}%`, top: `${hotspot.y}%`, transform: 'translate(-50%, -50%)' }}
              >
                {/* Pulsing pin */}
                <button
                  className={cn(
                    'font-[inherit] relative w-8 h-8 rounded-full bg-white shadow-lg border-2 border-primary flex items-center justify-center transition-transform',
                    'hover:scale-110 focus:outline-none',
                    isActive && 'scale-110',
                  )}
                  onClick={() => setActiveHotspot(isActive ? null : idx)}
                  aria-label={`View ${hotspot.product_name}`}
                >
                  {/* Ripple */}
                  <span className="absolute inset-0 rounded-full bg-primary/20 animate-ping" />
                  <span className="relative block w-3 h-3 rounded-full bg-primary" />
                </button>

                {/* Tooltip card */}
                {isActive && (
                  <div
                    className={cn(
                      'absolute z-20 w-56 bg-white rounded-xl shadow-2xl border p-3',
                      hotspot.x > 60 ? 'right-full mr-3' : 'left-full ml-3',
                      hotspot.y > 60 ? 'bottom-0' : 'top-0',
                    )}
                  >
                    {/* Close */}
                    <button
                      className="font-[inherit] absolute top-2 right-2 text-muted-foreground hover:text-foreground"
                      onClick={(e) => { e.stopPropagation(); setActiveHotspot(null); }}
                    >
                      <X className="w-3 h-3" />
                    </button>

                    {hotspot.product_image && (
                      <img src={hotspot.product_image} alt={hotspot.product_name} className="w-full aspect-square object-cover rounded-lg mb-2" />
                    )}
                    <p className="font-semibold text-sm line-clamp-2 mb-1">{hotspot.product_name || 'Product'}</p>
                    {hotspot.product_price && (
                      <p className="text-sm font-bold mb-2">{formatPrice(hotspot.product_price)}</p>
                    )}
                    <div className="flex gap-2">
                      {hotspot.product_slug && (
                        <Link
                          to={`/product/${hotspot.product_slug}`}
                          className="flex-1 text-xs text-center py-1.5 border border-border rounded-lg hover:bg-muted transition-colors"
                        >
                          View
                        </Link>
                      )}
                      <button
                        onClick={(e) => handleAddToCart(hotspot, e)}
                        className="font-[inherit] flex-1 text-xs py-1.5 bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center justify-center gap-1"
                      >
                        <ShoppingCart className="w-3 h-3" /> Add
                      </button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
