/**
 * Product Carousel Widget
 * 
 * Shows multiple products in a horizontal carousel.
 */

import { useState, useRef } from 'react'
import { motion } from 'framer-motion'
import { ChevronLeft, ChevronRight, ShoppingCart, ExternalLink, Star, Tag, Package } from 'lucide-react'
import { t } from '@/lib/i18n'

interface Product {
  id: number
  name: string
  price: string
  regular_price?: string
  formatted_price: string
  currency: string
  image?: string
  url: string
  is_on_sale: boolean
  in_stock: boolean
  average_rating?: number
  recommendation_type?: string
}

interface ProductCarouselWidgetProps {
  config: {
    title?: string
    products: Product[]
    show_add_to_cart?: boolean
    is_rtl?: boolean
  }
  onAddToCart?: (productId: number) => void
  onViewProduct?: (productId: number) => void
}

export function ProductCarouselWidget({ config, onAddToCart, onViewProduct }: ProductCarouselWidgetProps) {
  const { title, products, show_add_to_cart = true, is_rtl = true } = config
  const [currentIndex, setCurrentIndex] = useState(0)
  const scrollRef = useRef<HTMLDivElement>(null)

  const visibleProducts = 2 // How many products visible at once
  const canScrollPrev = currentIndex > 0
  const canScrollNext = currentIndex < products.length - visibleProducts

  const scroll = (direction: 'prev' | 'next') => {
    if (direction === 'prev' && canScrollPrev) {
      setCurrentIndex(prev => prev - 1)
    } else if (direction === 'next' && canScrollNext) {
      setCurrentIndex(prev => prev + 1)
    }
  }

  if (products.length === 0) {
    return null
  }

  return (
    <motion.div
      className="bg-white rounded-xl shadow-lg border border-gray-100 p-4"
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      dir={is_rtl ? 'rtl' : 'ltr'}
    >
      {/* Header */}
      {title && (
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-semibold text-gray-800">{title}</h3>
          
          {/* Navigation buttons */}
          {products.length > visibleProducts && (
            <div className="flex gap-1">
              <button
                onClick={() => scroll(is_rtl ? 'next' : 'prev')}
                disabled={is_rtl ? !canScrollNext : !canScrollPrev}
                className={`p-1.5 rounded-lg transition-colors ${
                  (is_rtl ? canScrollNext : canScrollPrev)
                    ? 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                    : 'bg-gray-50 text-gray-300 cursor-not-allowed'
                }`}
              >
                <ChevronRight className="w-4 h-4" />
              </button>
              <button
                onClick={() => scroll(is_rtl ? 'prev' : 'next')}
                disabled={is_rtl ? !canScrollPrev : !canScrollNext}
                className={`p-1.5 rounded-lg transition-colors ${
                  (is_rtl ? canScrollPrev : canScrollNext)
                    ? 'bg-gray-100 hover:bg-gray-200 text-gray-700'
                    : 'bg-gray-50 text-gray-300 cursor-not-allowed'
                }`}
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
            </div>
          )}
        </div>
      )}

      {/* Products */}
      <div className="overflow-hidden" ref={scrollRef}>
        <motion.div
          className="flex gap-3"
          animate={{ 
            x: is_rtl 
              ? currentIndex * (160 + 12) 
              : -(currentIndex * (160 + 12))
          }}
          transition={{ type: 'spring', stiffness: 300, damping: 30 }}
        >
          {products.map((product, index) => (
            <motion.div
              key={product.id}
              className="flex-shrink-0 w-40"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ delay: index * 0.05 }}
            >
              <div className="bg-gray-50 rounded-xl overflow-hidden border border-gray-100 hover:border-primary/30 transition-colors">
                {/* Image */}
                <div className="relative aspect-square bg-white">
                  {product.image ? (
                    <img
                      src={product.image}
                      alt={product.name}
                      className="w-full h-full object-cover"
                      loading="lazy"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <Package className="w-10 h-10 text-gray-300" />
                    </div>
                  )}
                  
                  {/* Sale badge */}
                  {product.is_on_sale && (
                    <div className="absolute top-2 start-2">
                      <span className="bg-red-500 text-white text-xs font-bold px-2 py-0.5 rounded-full flex items-center gap-0.5">
                        <Tag className="w-3 h-3" />
                        {t('Sale')}
                      </span>
                    </div>
                  )}

                  {/* Out of stock overlay */}
                  {!product.in_stock && (
                    <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
                      <span className="bg-gray-900 text-white text-xs px-2 py-1 rounded">{t('Sold out')}</span>
                    </div>
                  )}
                </div>

                {/* Info */}
                <div className="p-3">
                  {/* Rating */}
                  {product.average_rating !== undefined && product.average_rating > 0 && (
                    <div className="flex items-center gap-0.5 mb-1">
                      <Star className="w-3 h-3 text-yellow-400 fill-yellow-400" />
                      <span className="text-xs text-gray-500">{product.average_rating.toFixed(1)}</span>
                    </div>
                  )}

                  {/* Name */}
                  <h4 className="text-sm font-medium text-gray-800 line-clamp-2 min-h-[2.5rem]">
                    {product.name}
                  </h4>

                  {/* Price */}
                  <div className="flex items-baseline gap-1 mt-1">
                    <span 
                      className="font-bold text-primary"
                      dangerouslySetInnerHTML={{ __html: product.formatted_price }}
                    />
                    {product.is_on_sale && product.regular_price && (
                      <span className="text-xs text-gray-400 line-through">
                        {product.currency}{product.regular_price}
                      </span>
                    )}
                  </div>

                  {/* Actions */}
                  <div className="flex gap-1.5 mt-2">
                    {show_add_to_cart && product.in_stock && (
                      <motion.button
                        onClick={() => onAddToCart?.(product.id)}
                        className="flex-1 flex items-center justify-center gap-1 bg-primary text-white py-1.5 rounded-lg text-xs font-medium hover:bg-primary/90 transition-colors"
                        whileHover={{ scale: 1.02 }}
                        whileTap={{ scale: 0.98 }}
                      >
                        <ShoppingCart className="w-3 h-3" />
                        {t('Add')}
                      </motion.button>
                    )}
                    <motion.a
                      href={product.url}
                      onClick={() => onViewProduct?.(product.id)}
                      className={`
                        flex items-center justify-center gap-1
                        ${show_add_to_cart && product.in_stock 
                          ? 'px-2 bg-gray-100 text-gray-700 hover:bg-gray-200' 
                          : 'flex-1 bg-primary text-white hover:bg-primary/90'
                        }
                        py-1.5 rounded-lg text-xs font-medium transition-colors
                      `}
                      whileHover={{ scale: 1.02 }}
                      whileTap={{ scale: 0.98 }}
                    >
                      <ExternalLink className="w-3 h-3" />
                      {(!show_add_to_cart || !product.in_stock) && t('View')}
                    </motion.a>
                  </div>
                </div>
              </div>
            </motion.div>
          ))}
        </motion.div>
      </div>

      {/* Dots indicator */}
      {products.length > visibleProducts && (
        <div className="flex justify-center gap-1.5 mt-3">
          {Array.from({ length: products.length - visibleProducts + 1 }).map((_, i) => (
            <button
              key={i}
              onClick={() => setCurrentIndex(i)}
              className={`w-1.5 h-1.5 rounded-full transition-colors ${
                i === currentIndex ? 'bg-primary' : 'bg-gray-300'
              }`}
            />
          ))}
        </div>
      )}
    </motion.div>
  )
}

export default ProductCarouselWidget

