'use client'

import { motion, AnimatePresence } from 'framer-motion'
import {
  X, Heart, Share2, Tag, BookOpen, Zap, TrendingDown, Star,
  Check, FlaskConical, Droplet, Volume2, ChevronLeft, ChevronRight,
  ShoppingCart, Plus, Minus,
} from 'lucide-react'
import { useCatalogStore } from '@/lib/store'
import {
  formatPrice, getEffectivePrice, getSavings, getProductImageStyle,
  getCategorySymbol, parseBenefits, parseIngredients, shareProduct,
} from '@/lib/catalog-utils'
import type { Product } from '@/lib/types'
import { useEffect, useState } from 'react'
import { ProductCard } from './product-card'

export function ProductDetail() {
  const {
    selectedProduct, setSelectedProduct, favorites, toggleFavorite,
    goToPage, cart, addToCart, incrementCart, decrementCart, setCartOpen,
  } = useCatalogStore()

  const [related, setRelated] = useState<Product[]>([])

  useEffect(() => {
    if (!selectedProduct) return
    fetch(`/api/products/${selectedProduct.code}`)
      .then(r => r.json())
      .then(res => setRelated(res.data?.related || []))
      .catch(() => {})

    // Lock body scroll
    document.body.style.overflow = 'hidden'
    return () => { document.body.style.overflow = '' }
  }, [selectedProduct])

  const cartItem = selectedProduct ? cart.find(i => i.code === selectedProduct.code) : undefined
  const inCartQty = cartItem?.qty || 0

  return (
    <AnimatePresence>
      {selectedProduct && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm overflow-y-auto"
          onClick={() => setSelectedProduct(null)}
        >
          <div className="min-h-screen flex items-start justify-center p-0 sm:p-4">
            <motion.div
              initial={{ scale: 0.95, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.95, opacity: 0, y: 20 }}
              transition={{ type: 'spring', damping: 28, stiffness: 300 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-white w-full max-w-5xl min-h-screen sm:min-h-0 sm:rounded-3xl shadow-2xl overflow-hidden my-0 sm:my-8"
            >
              {/* Close button */}
              <button
                onClick={() => setSelectedProduct(null)}
                className="absolute top-4 right-4 z-20 w-10 h-10 rounded-full bg-white/90 backdrop-blur shadow-md flex items-center justify-center hover:bg-white transition-colors"
              >
                <X className="w-5 h-5 text-gray-700" />
              </button>

              <div className="grid md:grid-cols-2 gap-0">
                {/* Left: Image */}
                <div
                  className="relative aspect-square md:aspect-auto md:min-h-[600px] flex items-center justify-center p-8"
                  style={{ background: getProductImageStyle(selectedProduct).bg }}
                >
                  <div className="text-center">
                    <div className="text-8xl mb-4 opacity-90">{getCategorySymbol(selectedProduct.category?.slug || '')}</div>
                    <div className="inline-block bg-white/70 backdrop-blur px-4 py-1.5 rounded-full text-sm font-mono font-bold text-gray-700 mb-2">
                      CÓD: {selectedProduct.code}
                    </div>
                    <div className="text-sm text-gray-600 font-medium">{selectedProduct.volume}</div>
                    {selectedProduct.fragrance && (
                      <div className="mt-2 inline-flex items-center gap-1 text-xs bg-white/60 px-3 py-1 rounded-full">
                        <Droplet className="w-3 h-3" /> {selectedProduct.fragrance}
                      </div>
                    )}
                  </div>

                  {/* Badges */}
                  <div className="absolute top-4 left-4 flex flex-col gap-2">
                    {selectedProduct.isLaunch && (
                      <Badge icon={<Zap className="w-3 h-3" />} text="LANÇAMENTO" color="bg-amber-400 text-black" />
                    )}
                    {selectedProduct.isLowerPriceYear && (
                      <Badge icon={<TrendingDown className="w-3 h-3" />} text="MENOR PREÇO DO ANO" color="bg-red-500 text-white" />
                    )}
                    {selectedProduct.isBestseller && (
                      <Badge icon={<Star className="w-3 h-3" />} text="MAIS VENDIDO" color="bg-black text-amber-400" />
                    )}
                  </div>
                </div>

                {/* Right: Details */}
                <div className="p-6 sm:p-8 overflow-y-auto max-h-[50vh] md:max-h-[600px]">
                  <div className="flex items-center gap-2 mb-3">
                    <span
                      className="text-[10px] font-bold uppercase tracking-wider px-2.5 py-1 rounded-full"
                      style={{
                        backgroundColor: `${selectedProduct.category?.color}20`,
                        color: selectedProduct.category?.color || '#F59E0B',
                      }}
                    >
                      {selectedProduct.category?.name}
                    </span>
                    <span className="text-[10px] text-gray-400">Código {selectedProduct.code}</span>
                  </div>

                  <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 leading-tight mb-3">
                    {selectedProduct.name}
                  </h1>

                  {/* Rating */}
                  <div className="flex items-center gap-2 mb-4">
                    <div className="flex">
                      {[1,2,3,4,5].map(i => (
                        <Star
                          key={i}
                          className={`w-4 h-4 ${i <= Math.round(selectedProduct.rating) ? 'fill-amber-400 text-amber-400' : 'text-gray-300'}`}
                        />
                      ))}
                    </div>
                    <span className="text-xs text-gray-500">{selectedProduct.rating.toFixed(1)} • Catálogo CP 03/2026</span>
                  </div>

                  {/* Price */}
                  <div className="bg-gradient-to-br from-amber-50 to-yellow-50 rounded-2xl p-5 mb-5 border border-amber-100">
                    {selectedProduct.promotionalPrice && selectedProduct.promotionalPrice < selectedProduct.price ? (
                      <>
                        <div className="flex items-center gap-2 mb-1">
                          {selectedProduct.discountPercent && (
                            <span className="bg-red-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                              -{selectedProduct.discountPercent}%
                            </span>
                          )}
                          <span className="text-sm text-gray-400 line-through">{formatPrice(selectedProduct.price)}</span>
                        </div>
                        <div className="flex items-baseline gap-2">
                          <span className="text-xs text-gray-600 font-medium">por apenas</span>
                        </div>
                        <div className="text-3xl font-bold text-red-600">
                          {formatPrice(getEffectivePrice(selectedProduct))}
                        </div>
                        {getSavings(selectedProduct) && (
                          <div className="mt-2 inline-flex items-center gap-1 text-xs bg-green-100 text-green-700 px-2 py-1 rounded-full font-medium">
                            <Check className="w-3 h-3" /> Você economiza {formatPrice(getSavings(selectedProduct))}
                          </div>
                        )}
                      </>
                    ) : (
                      <div className="text-3xl font-bold text-gray-900">
                        {formatPrice(selectedProduct.price)}
                      </div>
                    )}
                  </div>

                  {/* Description */}
                  {selectedProduct.description && (
                    <div className="mb-5">
                      <h3 className="text-xs font-bold text-gray-900 uppercase tracking-wider mb-2">Descrição</h3>
                      <p className="text-sm text-gray-600 leading-relaxed">{selectedProduct.description}</p>
                    </div>
                  )}

                  {/* Benefits */}
                  {selectedProduct.benefits && (
                    <div className="mb-5">
                      <h3 className="text-xs font-bold text-gray-900 uppercase tracking-wider mb-2 flex items-center gap-1.5">
                        <Check className="w-3.5 h-3.5 text-green-500" /> Benefícios
                      </h3>
                      <ul className="space-y-1.5">
                        {parseBenefits(selectedProduct.benefits).map((b, i) => (
                          <li key={i} className="flex items-start gap-2 text-sm text-gray-600">
                            <span className="w-1.5 h-1.5 rounded-full bg-amber-400 mt-1.5 flex-shrink-0" />
                            {b}
                          </li>
                        ))}
                      </ul>
                    </div>
                  )}

                  {/* Ingredients */}
                  {selectedProduct.ingredients && (
                    <div className="mb-5">
                      <h3 className="text-xs font-bold text-gray-900 uppercase tracking-wider mb-2 flex items-center gap-1.5">
                        <FlaskConical className="w-3.5 h-3.5 text-purple-500" /> Ativos / Ingredientes
                      </h3>
                      <div className="flex flex-wrap gap-1.5">
                        {parseIngredients(selectedProduct.ingredients).map((ing, i) => (
                          <span key={i} className="text-xs bg-purple-50 text-purple-700 px-2.5 py-1 rounded-full font-medium">
                            {ing}
                          </span>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Info grid */}
                  <div className="grid grid-cols-2 gap-3 mb-5">
                    <InfoCard icon={<Volume2 className="w-4 h-4" />} label="Volume" value={selectedProduct.volume || '-'} />
                    <InfoCard
                      icon={<BookOpen className="w-4 h-4" />}
                      label="Página no catálogo"
                      value={`${selectedProduct.page}`}
                      onClick={() => {
                        goToPage(selectedProduct.page)
                        setSelectedProduct(null)
                      }}
                    />
                    {selectedProduct.activeIngredient && (
                      <InfoCard icon={<FlaskConical className="w-4 h-4" />} label="Ativo principal" value={selectedProduct.activeIngredient} />
                    )}
                    {selectedProduct.fragrance && (
                      <InfoCard icon={<Droplet className="w-4 h-4" />} label="Fragrância" value={selectedProduct.fragrance} />
                    )}
                  </div>

                  {/* Actions */}
                  <div className="space-y-2 pt-2">
                    {/* Primary: add to cart / qty stepper */}
                    {inCartQty === 0 ? (
                      <button
                        onClick={() => addToCart(selectedProduct.code, 1)}
                        className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm bg-amber-400 text-black hover:bg-amber-500 active:scale-[0.98] transition-all shadow-sm"
                      >
                        <ShoppingCart className="w-4 h-4" />
                        Adicionar ao carrinho
                        <span className="ml-1 px-2 py-0.5 rounded-full bg-black/10 text-[11px]">
                          {formatPrice(getEffectivePrice(selectedProduct))}
                        </span>
                      </button>
                    ) : (
                      <div className="flex gap-2">
                        <div className="inline-flex items-center rounded-xl bg-amber-50 border-2 border-amber-200 overflow-hidden">
                          <button
                            onClick={() => decrementCart(selectedProduct.code)}
                            className="w-12 h-12 flex items-center justify-center text-amber-700 hover:bg-amber-100 transition-colors"
                            aria-label="Diminuir"
                          >
                            <Minus className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => setCartOpen(true)}
                            className="min-w-[60px] h-12 px-2 flex flex-col items-center justify-center text-amber-900 hover:bg-amber-100/50 transition-colors"
                            title="Ver carrinho"
                          >
                            <span className="text-lg font-bold leading-none">{inCartQty}</span>
                            <span className="text-[9px] font-semibold uppercase opacity-70">no carrinho</span>
                          </button>
                          <button
                            onClick={() => incrementCart(selectedProduct.code)}
                            className="w-12 h-12 flex items-center justify-center text-amber-700 hover:bg-amber-100 transition-colors"
                            aria-label="Aumentar"
                          >
                            <Plus className="w-4 h-4" />
                          </button>
                        </div>
                        <button
                          onClick={() => setCartOpen(true)}
                          className="flex-1 flex items-center justify-center gap-2 py-3.5 rounded-xl font-bold text-sm bg-neutral-900 text-white hover:bg-neutral-800 transition-colors"
                        >
                          <ShoppingCart className="w-4 h-4" /> Ver carrinho
                        </button>
                      </div>
                    )}

                    {/* Secondary: favorite + share */}
                    <div className="flex gap-2">
                      <button
                        onClick={() => toggleFavorite(selectedProduct.code)}
                        className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl font-semibold text-sm transition-all ${
                          favorites.includes(selectedProduct.code)
                            ? 'bg-red-50 text-red-600 border-2 border-red-200'
                            : 'bg-gray-50 text-gray-700 border-2 border-gray-200 hover:border-amber-300'
                        }`}
                      >
                        <Heart className={`w-4 h-4 ${favorites.includes(selectedProduct.code) ? 'fill-red-500' : ''}`} />
                        {favorites.includes(selectedProduct.code) ? 'Favoritado' : 'Favoritar'}
                      </button>
                      <button
                        onClick={() => shareProduct(selectedProduct)}
                        className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl font-semibold text-sm bg-gray-50 text-gray-700 border-2 border-gray-200 hover:border-amber-300 transition-all"
                      >
                        <Share2 className="w-4 h-4" /> Compartilhar
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              {/* Related products */}
              {related.length > 0 && (
                <div className="border-t border-gray-100 p-6 sm:p-8">
                  <h2 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
                    <span className="w-1 h-5 bg-amber-400 rounded-full" />
                    Produtos Relacionados
                  </h2>
                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
                    {related.slice(0, 4).map((p, i) => (
                      <ProductCard key={p.id} product={p} index={i} />
                    ))}
                  </div>
                </div>
              )}
            </motion.div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}

function Badge({ icon, text, color }: { icon: React.ReactNode; text: string; color: string }) {
  return (
    <span className={`inline-flex items-center gap-1 ${color} text-[10px] font-bold px-2.5 py-1 rounded-full shadow-sm`}>
      {icon} {text}
    </span>
  )
}

function InfoCard({
  icon, label, value, onClick,
}: {
  icon: React.ReactNode
  label: string
  value: string
  onClick?: () => void
}) {
  return (
    <div
      onClick={onClick}
      className={`bg-gray-50 rounded-xl p-3 ${onClick ? 'cursor-pointer hover:bg-amber-50 transition-colors' : ''}`}
    >
      <div className="flex items-center gap-1.5 text-[10px] text-gray-400 uppercase tracking-wider mb-1">
        {icon} {label}
      </div>
      <div className="text-sm font-semibold text-gray-900">{value}</div>
    </div>
  )
}
