'use client'

import { motion, AnimatePresence } from 'framer-motion'
import { useEffect, useState, useMemo } from 'react'
import { useCatalogStore } from '@/lib/store'
import type { Product } from '@/lib/types'
import { ShoppingCart, X, Plus, Minus, Trash2, Package, Tag, Share2, MessageCircle } from 'lucide-react'
import { formatPrice, getEffectivePrice, getCategorySymbol } from '@/lib/catalog-utils'
import { buildWhatsAppUrl, buildShareText } from '@/lib/whatsapp-message'

export function CartDrawer() {
  const {
    cartOpen, setCartOpen, cart, incrementCart, decrementCart, removeFromCart, clearCart,
    setSelectedProduct, goToPage, products: cachedProducts,
  } = useCatalogStore()
  // Distribuidor vinculado à sessão (vem do deep link ?d=slug). Quando
  // presente, o checkout abre o chat DIRETO com ele em vez do wa.me genérico.
  const distributor = useCatalogStore(s => s.currentDistributor)

  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(false)
  const [checkoutFlash, setCheckoutFlash] = useState(false)

  // Resolve cart item products from the preloaded cache (no API call).
  // Falls back to a direct fetch only if the cache is somehow empty.
  useEffect(() => {
    if (!cartOpen) return
    const codes = cart.map(i => i.code)
    if (codes.length === 0) return
    if (cachedProducts.length > 0) return
    // Fallback: cache not ready yet
    let cancelled = false
    queueMicrotask(() => { if (!cancelled) setLoading(true) })
    fetch(`/api/products?limit=500`)
      .then(r => r.json())
      .then(res => {
        if (cancelled) return
        const prods: Product[] = res.data || []
        setProducts(codes.map(c => prods.find(p => p.code === c)).filter(Boolean) as Product[])
      })
      .catch(() => {})
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [cartOpen, cart, cachedProducts])

  // Derive the products list from the cache (or the fallback fetch).
  // When the cart is empty, this naturally resolves to [].
  const resolvedProducts = useMemo(() => {
    if (cart.length === 0) return []
    const source = cachedProducts.length > 0 ? cachedProducts : products
    return cart.map(i => source.find(p => p.code === i.code)).filter(Boolean) as Product[]
  }, [cart, cachedProducts, products])

  const items = useMemo(() => {
    return cart
      .map(item => {
        const product = resolvedProducts.find(p => p.code === item.code)
        if (!product) return null
        return { ...item, product, unitPrice: getEffectivePrice(product) }
      })
      .filter(Boolean) as Array<{ code: string; qty: number; product: Product; unitPrice: number }>
  }, [cart, resolvedProducts])

  const subtotal = items.reduce((s, i) => s + i.unitPrice * i.qty, 0)
  const totalItems = items.reduce((s, i) => s + i.qty, 0)
  const totalSavings = items.reduce((s, i) => {
    if (i.product.promotionalPrice && i.product.promotionalPrice < i.product.price) {
      return s + (i.product.price - i.product.promotionalPrice) * i.qty
    }
    return s
  }, 0)

  const handleCheckout = () => {
    // Gera a URL do WhatsApp. Se há distribuidor vinculado, a mensagem vai
    // DIRETO para o número dele (wa.me/{whatsapp}?text=...). Caso contrário,
    // cai no fluxo genérico (wa.me/?text=...), deixando o cliente escolher.
    const url = buildWhatsAppUrl(items, distributor?.whatsapp, distributor?.name)
    window.open(url, '_blank')
    setCheckoutFlash(true)
    setTimeout(() => setCheckoutFlash(false), 2000)
  }

  const shareCart = async () => {
    const msg = buildShareText(items)
    try {
      if (navigator.share) await navigator.share({ title: 'Meu carrinho Abelha Rainha', text: msg })
      else if (navigator.clipboard) await navigator.clipboard.writeText(msg)
    } catch { /* ignore */ }
  }

  return (
    <AnimatePresence>
      {cartOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setCartOpen(false)}
            className="fixed inset-0 bg-black/40 z-40 backdrop-blur-sm"
          />
          <motion.aside
            initial={{ x: '100%' }}
            animate={{ x: 0 }}
            exit={{ x: '100%' }}
            transition={{ type: 'spring', damping: 30, stiffness: 280 }}
            className="fixed top-0 right-0 bottom-0 w-96 max-w-[90vw] bg-white z-40 shadow-2xl flex flex-col"
          >
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b border-neutral-100 flex-shrink-0">
              <div className="flex items-center gap-2">
                <div className="w-9 h-9 rounded-full bg-amber-400 flex items-center justify-center relative">
                  <ShoppingCart className="w-4 h-4 text-black" />
                  {totalItems > 0 && (
                    <span className="absolute -top-1 -right-1 min-w-[16px] h-4 px-1 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center">
                      {totalItems}
                    </span>
                  )}
                </div>
                <div>
                  <div className="text-sm font-bold text-neutral-900">Carrinho</div>
                  <div className="text-[10px] text-neutral-500">
                    {totalItems} {totalItems === 1 ? 'item' : 'itens'}
                  </div>
                </div>
              </div>
              <button
                onClick={() => setCartOpen(false)}
                className="p-2 rounded-lg hover:bg-neutral-100"
                aria-label="Fechar"
              >
                <X className="w-5 h-5 text-neutral-500" />
              </button>
            </div>

            {/* Items list */}
            <div className="flex-1 overflow-y-auto">
              {loading ? (
                <div className="p-4 space-y-3">
                  {Array.from({ length: 3 }).map((_, i) => (
                    <div key={i} className="h-20 bg-neutral-100 rounded-xl animate-pulse" />
                  ))}
                </div>
              ) : items.length === 0 ? (
                <div className="text-center py-16 px-6 text-neutral-400">
                  <ShoppingCart className="w-12 h-12 mx-auto mb-3 opacity-20" />
                  <p className="text-sm font-medium text-neutral-500">Seu carrinho está vazio</p>
                  <p className="text-xs mt-1">Adicione produtos clicando no botão <span className="text-amber-600 font-semibold">+ Adicionar</span> em qualquer produto.</p>
                  <button
                    onClick={() => {
                      setCartOpen(false)
                      useCatalogStore.getState().setSearchOpen(true)
                    }}
                    className="mt-4 inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-amber-400 text-black text-sm font-semibold hover:bg-amber-500 transition-colors"
                  >
                    <Package className="w-4 h-4" /> Buscar produtos
                  </button>
                </div>
              ) : (
                <div className="p-3 space-y-2">
                  {items.map(({ code, qty, product, unitPrice }) => {
                    const hasPromo = product.promotionalPrice && product.promotionalPrice < product.price
                    return (
                      <div
                        key={code}
                        className="group flex items-center gap-3 p-2.5 rounded-xl border border-neutral-100 hover:border-amber-200 hover:bg-amber-50/50 transition-colors"
                      >
                        {/* Thumbnail */}
                        <button
                          onClick={() => { setSelectedProduct(product) }}
                          className="relative flex-shrink-0 w-12 h-16 rounded-lg overflow-hidden bg-neutral-100 border border-neutral-200 hover:ring-2 hover:ring-amber-300"
                          title="Ver detalhes"
                        >
                          <img
                            src={`/catalog-pages-thumbs/page-${String(product.page).padStart(3, '0')}.webp`}
                            alt=""
                            className="w-full h-full object-cover"
                            loading="lazy"
                          />
                          <span className="absolute bottom-0 inset-x-0 text-[8px] text-white bg-black/70 text-center font-mono py-0.5">
                            p.{product.page}
                          </span>
                        </button>

                        {/* Info */}
                        <div className="flex-1 min-w-0">
                          <button
                            onClick={() => setSelectedProduct(product)}
                            className="block text-left"
                          >
                            <div className="text-[10px] font-mono text-neutral-400">#{product.code}</div>
                            <h3 className="text-sm font-semibold text-neutral-900 leading-tight truncate hover:text-amber-700">
                              {product.name}
                            </h3>
                          </button>
                          <div className="flex items-center gap-1.5 mt-0.5">
                            {product.category && (
                              <span className="text-[10px] text-neutral-400 flex items-center gap-0.5">
                                {getCategorySymbol(product.category.slug)} {product.category.name}
                              </span>
                            )}
                          </div>
                          <div className="flex items-baseline gap-1.5 mt-1">
                            {hasPromo && (
                              <span className="text-[10px] text-neutral-400 line-through">{formatPrice(product.price)}</span>
                            )}
                            <span className={`text-xs font-bold ${hasPromo ? 'text-red-600' : 'text-neutral-900'}`}>
                              {formatPrice(unitPrice)}
                            </span>
                          </div>
                        </div>

                        {/* Qty stepper */}
                        <div className="flex flex-col items-center gap-1 flex-shrink-0">
                          <div className="inline-flex items-center rounded-full bg-neutral-100 border border-neutral-200 overflow-hidden">
                            <button
                              onClick={() => decrementCart(code)}
                              className="w-6 h-6 flex items-center justify-center text-neutral-700 hover:bg-neutral-200 transition-colors"
                              aria-label="Diminuir"
                            >
                              <Minus className="w-3 h-3" />
                            </button>
                            <span className="min-w-[20px] text-xs font-bold text-neutral-900 text-center">
                              {qty}
                            </span>
                            <button
                              onClick={() => incrementCart(code)}
                              className="w-6 h-6 flex items-center justify-center text-neutral-700 hover:bg-neutral-200 transition-colors"
                              aria-label="Aumentar"
                            >
                              <Plus className="w-3 h-3" />
                            </button>
                          </div>
                          <button
                            onClick={() => removeFromCart(code)}
                            className="text-[9px] text-neutral-400 hover:text-red-500 flex items-center gap-0.5 transition-colors"
                            aria-label="Remover do carrinho"
                          >
                            <Trash2 className="w-2.5 h-2.5" /> Remover
                          </button>
                        </div>
                      </div>
                    )
                  })}

                  {/* Clear all */}
                  <button
                    onClick={() => {
                      if (confirm('Deseja remover todos os itens do carrinho?')) clearCart()
                    }}
                    className="mt-3 w-full text-center text-[11px] text-neutral-400 hover:text-red-500 py-1.5 flex items-center justify-center gap-1 transition-colors"
                  >
                    <Trash2 className="w-3 h-3" /> Esvaziar carrinho
                  </button>
                </div>
              )}
            </div>

            {/* Footer — totals + checkout */}
            {items.length > 0 && (
              <div className="flex-shrink-0 border-t border-neutral-100 bg-white">
                {/* Savings badge */}
                {totalSavings > 0 && (
                  <div className="px-4 pt-3">
                    <div className="bg-green-50 border border-green-200 rounded-lg px-3 py-2 flex items-center gap-2">
                      <Tag className="w-3.5 h-3.5 text-green-600" />
                      <span className="text-[11px] font-semibold text-green-700">
                        Você economiza {formatPrice(totalSavings)} nesta compra!
                      </span>
                    </div>
                  </div>
                )}

                {/* Totals */}
                <div className="px-4 py-3 space-y-1">
                  <div className="flex justify-between text-xs text-neutral-500">
                    <span>Subtotal ({totalItems} {totalItems === 1 ? 'item' : 'itens'})</span>
                    <span className="font-mono">{formatPrice(subtotal)}</span>
                  </div>
                  <div className="flex justify-between items-baseline pt-1 border-t border-neutral-100">
                    <span className="text-sm font-bold text-neutral-900">Total</span>
                    <span className="text-xl font-bold text-amber-600">{formatPrice(subtotal)}</span>
                  </div>
                </div>

                {/* Actions */}
                <div className="p-4 pt-2 space-y-2">
                  {/* Indicador do distribuidor vinculado — deixa o cliente
                      saber para onde o pedido será enviado. */}
                  {distributor && (
                    <div className="flex items-center gap-2 bg-green-50 border border-green-200 rounded-lg px-3 py-1.5">
                      <MessageCircle className="w-3.5 h-3.5 text-green-600 flex-shrink-0" />
                      <span className="text-[11px] text-green-800 leading-tight">
                        Pedido enviado para <span className="font-bold">{distributor.name}</span>
                      </span>
                    </div>
                  )}
                  <button
                    onClick={handleCheckout}
                    className={`w-full flex items-center justify-center gap-2 py-3 rounded-xl font-bold text-sm transition-all ${
                      checkoutFlash
                        ? 'bg-green-500 text-white'
                        : 'bg-amber-400 text-black hover:bg-amber-500 active:scale-[0.98]'
                    }`}
                  >
                    {checkoutFlash ? (
                      <>✓ Pedido enviado! Verifique o WhatsApp</>
                    ) : (
                      <>
                        <ShoppingCart className="w-4 h-4" /> Finalizar no WhatsApp
                      </>
                    )}
                  </button>
                  <div className="flex gap-2">
                    <button
                      onClick={shareCart}
                      className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold bg-neutral-100 text-neutral-700 hover:bg-neutral-200 transition-colors"
                    >
                      <Share2 className="w-3.5 h-3.5" /> Compartilhar
                    </button>
                    <button
                      onClick={() => {
                        // Jump to the page of the first item
                        if (items[0]) {
                          setCartOpen(false)
                          goToPage(items[0].product.page)
                        }
                      }}
                      className="flex-1 flex items-center justify-center gap-1.5 py-2 rounded-xl text-xs font-semibold bg-neutral-100 text-neutral-700 hover:bg-neutral-200 transition-colors"
                    >
                      <Package className="w-3.5 h-3.5" /> Ver no catálogo
                    </button>
                  </div>
                </div>
              </div>
            )}
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  )
}
