'use client'

import { motion, AnimatePresence } from 'framer-motion'
import { useEffect, useState } from 'react'
import { Check, ShoppingCart, X } from 'lucide-react'
import { useCatalogStore } from '@/lib/store'
import { formatPrice, getEffectivePrice, getCategorySymbol } from '@/lib/catalog-utils'

/**
 * CartToast — global confirmation that appears whenever a product is added
 * to the cart (from any source: product detail modal, inline card button,
 * search drawer, favorites drawer, etc.).
 *
 * Trigger: `lastAdded` in the store (set by `addToCart` + `incrementCart`).
 *
 * Architecture: the parent reads `lastAdded` and `cartOpen` from the store.
 * Each new add (new `lastAdded.timestamp`) renders a fresh `<CartToastItem>`
 * instance via `key`, which starts visible and auto-dismisses itself after
 * 3s via a `setTimeout` callback (no synchronous setState-in-effect).
 *
 * Suppresses itself while the cart drawer is open — the user can already see
 * the quantity change in the drawer, so a toast would be redundant.
 *
 * z-index is 60 so it appears above the product detail modal (z-50) when the
 * user adds from inside the modal.
 */
export function CartToast() {
  const lastAdded = useCatalogStore(s => s.lastAdded)
  const cartOpen = useCatalogStore(s => s.cartOpen)

  // Don't render the toast if there's nothing to show, or if the cart drawer is
  // open (the user can already see the qty change there).
  if (!lastAdded || cartOpen) return null

  // Keying on the timestamp means each new add creates a fresh toast
  // instance with its own auto-dismiss timer + enter animation.
  return <CartToastItem key={lastAdded.timestamp} />
}

function CartToastItem() {
  const lastAdded = useCatalogStore(s => s.lastAdded)!
  const products = useCatalogStore(s => s.products)
  const cart = useCatalogStore(s => s.cart)
  const setCartOpen = useCatalogStore(s => s.setCartOpen)

  const [visible, setVisible] = useState(true)

  // Auto-dismiss after 3s. setState lives inside the timer callback (not
  // synchronous in the effect body), so this doesn't trigger the
  // react-hooks/set-state-in-effect rule.
  useEffect(() => {
    const t = setTimeout(() => setVisible(false), 3000)
    return () => clearTimeout(t)
  }, [])

  const product = products.find(p => p.code === lastAdded.code)
  if (!product) return null

  const cartTotal = cart.reduce((sum, item) => {
    const p = products.find(pp => pp.code === item.code)
    return sum + (p ? getEffectivePrice(p) * item.qty : 0)
  }, 0)
  const cartCount = cart.reduce((s, i) => s + i.qty, 0)

  const openCart = () => {
    // Opening the cart drawer makes the parent return null (cartOpen=true),
    // which unmounts this toast. The cart drawer's own slide-in animation
    // provides the visual transition.
    setCartOpen(true)
  }

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          role="status"
          aria-live="polite"
          initial={{ opacity: 0, y: 60, scale: 0.92 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: 60, scale: 0.92 }}
          transition={{ type: 'spring', damping: 26, stiffness: 320 }}
          className="fixed bottom-4 left-1/2 -translate-x-1/2 z-[60] w-[calc(100vw-1.5rem)] max-w-md pointer-events-auto"
        >
          <div className="relative flex items-stretch gap-3 bg-white rounded-2xl shadow-2xl ring-1 ring-amber-200/70 overflow-hidden">
            {/* Green accent stripe on the left */}
            <div className="w-1.5 bg-green-500 flex-shrink-0" />

            {/* Icon */}
            <div className="flex items-center pl-1">
              <div className="w-10 h-10 rounded-full bg-green-500 flex items-center justify-center flex-shrink-0 shadow-sm">
                <Check className="w-5 h-5 text-white" strokeWidth={3} />
              </div>
            </div>

            {/* Body: product name + qty */}
            <div className="flex-1 min-w-0 py-2.5">
              <div className="text-[10px] font-bold uppercase tracking-wider text-green-600 leading-tight">
                Adicionado ao carrinho
              </div>
              <div className="flex items-center gap-1.5 min-w-0">
                {product.category && (
                  <span className="text-xs flex-shrink-0">
                    {getCategorySymbol(product.category.slug)}
                  </span>
                )}
                <span className="text-sm font-bold text-neutral-900 truncate">
                  {product.name}
                </span>
              </div>
              <div className="text-[11px] text-neutral-500 leading-tight">
                {lastAdded.qty > 1 ? `${lastAdded.qty}x ` : ''}
                {formatPrice(getEffectivePrice(product))} cada
              </div>
            </div>

            {/* Right: cart total + actions */}
            <div className="flex flex-col justify-center items-end gap-0.5 pr-3 py-2.5 pl-2 border-l border-neutral-100 flex-shrink-0">
              <div className="text-[9px] uppercase tracking-wider text-neutral-400 font-semibold">
                Total carrinho
              </div>
              <div className="text-base font-bold text-amber-600 leading-tight tabular-nums">
                {formatPrice(cartTotal)}
              </div>
              <button
                onClick={openCart}
                className="mt-0.5 inline-flex items-center gap-1 text-[11px] font-bold text-amber-700 hover:text-amber-800 bg-amber-50 hover:bg-amber-100 px-2 py-0.5 rounded-full transition-colors"
              >
                <ShoppingCart className="w-3 h-3" />
                Ver
                {cartCount > 0 && (
                  <span className="ml-0.5 min-w-[16px] h-4 px-1 bg-red-500 text-white text-[9px] font-bold rounded-full flex items-center justify-center">
                    {cartCount}
                  </span>
                )}
              </button>
            </div>

            {/* Close (X) */}
            <button
              onClick={() => setVisible(false)}
              className="absolute top-1.5 right-1.5 w-6 h-6 rounded-full flex items-center justify-center text-neutral-300 hover:text-neutral-600 hover:bg-neutral-100 transition-colors"
              aria-label="Fechar aviso"
            >
              <X className="w-3.5 h-3.5" />
            </button>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
