'use client'

import { motion, AnimatePresence } from 'framer-motion'
import { useEffect, useState } from 'react'
import { useCatalogStore } from '@/lib/store'
import type { Product } from '@/lib/types'
import { Heart, Clock, X, Package, MapPin } from 'lucide-react'
import { formatPrice, getEffectivePrice, getCategorySymbol } from '@/lib/catalog-utils'
import { MiniCartButton } from './mini-cart-button'

export function FavoritesDrawer() {
  const {
    favoritesOpen, setFavoritesOpen, favorites, recentlyViewed,
    setSelectedProduct, goToPage, toggleFavorite, products: cachedProducts,
  } = useCatalogStore()
  const [favProducts, setFavProducts] = useState<Product[]>([])
  const [recentProducts, setRecentProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!favoritesOpen) return
    let cancelled = false
    const allCodes = [...favorites, ...recentlyViewed]

    // Resolve from the preloaded cache (no API call) — instant.
    if (cachedProducts.length > 0) {
      setFavProducts(favorites.map(code => cachedProducts.find(p => p.code === code)).filter(Boolean) as Product[])
      setRecentProducts(recentlyViewed.map(code => cachedProducts.find(p => p.code === code)).filter(Boolean) as Product[])
      setLoading(false)
      return
    }

    // Fallback: cache not ready — fetch once
    const run = async () => {
      setLoading(true)
      if (allCodes.length === 0) {
        if (cancelled) return
        setFavProducts([])
        setRecentProducts([])
        setLoading(false)
        return
      }
      try {
        const res = await fetch(`/api/products?limit=500`).then(r => r.json())
        if (cancelled) return
        const prods: Product[] = res.data || []
        setFavProducts(favorites.map(code => prods.find(p => p.code === code)).filter(Boolean) as Product[])
        setRecentProducts(recentlyViewed.map(code => prods.find(p => p.code === code)).filter(Boolean) as Product[])
      } catch {
        /* ignore */
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    run()
    return () => { cancelled = true }
  }, [favoritesOpen, favorites, recentlyViewed, cachedProducts])

  return (
    <AnimatePresence>
      {favoritesOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setFavoritesOpen(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-full sm:w-[440px] max-w-[92vw] bg-white z-40 shadow-2xl flex flex-col"
          >
            <div className="flex-shrink-0 p-4 border-b border-neutral-100 flex items-center justify-between">
              <h2 className="text-base font-bold text-neutral-900 flex items-center gap-2">
                <Heart className="w-4 h-4 text-red-500 fill-red-500" />
                Meus Favoritos
                <span className="text-xs font-normal text-neutral-400">({favProducts.length})</span>
              </h2>
              <button
                onClick={() => setFavoritesOpen(false)}
                className="p-1.5 rounded-lg hover:bg-neutral-100"
                aria-label="Fechar"
              >
                <X className="w-5 h-5 text-neutral-500" />
              </button>
            </div>

            <div className="flex-1 min-h-0 overflow-y-auto p-3">
              {loading ? (
                <div className="space-y-2">
                  {Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="h-20 bg-neutral-100 rounded-xl animate-pulse" />
                  ))}
                </div>
              ) : favProducts.length === 0 ? (
                <div className="text-center py-12 text-neutral-400">
                  <Heart className="w-12 h-12 mx-auto mb-3 opacity-30" />
                  <p className="text-sm font-medium text-neutral-500">Nenhum favorito ainda</p>
                  <p className="text-xs mt-1">Busque produtos e clique no coração para salvá-los</p>
                  <button
                    onClick={() => {
                      setFavoritesOpen(false)
                      useCatalogStore.getState().setSearchOpen(true)
                    }}
                    className="mt-4 px-4 py-2 bg-amber-400 text-black text-xs font-bold rounded-full hover:bg-amber-500"
                  >
                    Buscar produtos
                  </button>
                </div>
              ) : (
                <div className="space-y-2 mb-6">
                  {favProducts.map(p => (
                    <FavoriteRow
                      key={p.id}
                      product={p}
                      isFavorite
                      onOpen={() => setSelectedProduct(p)}
                      onJump={() => { goToPage(p.page); setFavoritesOpen(false) }}
                      onToggle={() => toggleFavorite(p.code)}
                    />
                  ))}
                </div>
              )}

              {/* Recently viewed */}
              {!loading && recentProducts.length > 0 && (
                <>
                  <div className="flex items-center gap-1.5 px-1 pt-4 pb-2 text-[10px] font-bold text-neutral-400 uppercase tracking-wider">
                    <Clock className="w-3.5 h-3.5" /> Últimos vistos
                  </div>
                  <div className="space-y-2">
                    {recentProducts.map(p => (
                      <FavoriteRow
                        key={p.id}
                        product={p}
                        isFavorite={favorites.includes(p.code)}
                        onOpen={() => setSelectedProduct(p)}
                        onJump={() => { goToPage(p.page); setFavoritesOpen(false) }}
                        onToggle={() => toggleFavorite(p.code)}
                      />
                    ))}
                  </div>
                </>
              )}
            </div>
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  )
}

function FavoriteRow({
  product, isFavorite, onOpen, onJump, onToggle,
}: {
  product: Product
  isFavorite: boolean
  onOpen: () => void
  onJump: () => void
  onToggle: () => void
}) {
  const price = getEffectivePrice(product)
  const hasPromo = product.promotionalPrice && product.promotionalPrice < product.price
  return (
    <div className="group flex items-center gap-3 p-2.5 rounded-xl hover:bg-amber-50 transition-colors border border-transparent hover:border-amber-100">
      <button
        onClick={onJump}
        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 na página ${product.page}`}
      >
        <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>

      <div className="flex-1 min-w-0 cursor-pointer" onClick={onOpen}>
        <div className="flex items-center gap-1.5 mb-0.5">
          <span className="text-[10px] font-mono text-neutral-400">#{product.code}</span>
          {product.category && (
            <span className="text-[10px] text-neutral-400 flex items-center gap-0.5">
              {getCategorySymbol(product.category.slug)} {product.category.name}
            </span>
          )}
        </div>
        <h3 className="text-sm font-semibold text-neutral-900 leading-tight truncate group-hover:text-amber-700">
          {product.name}
        </h3>
        <div className="flex items-center justify-between gap-2 mt-1">
          <div className="flex items-baseline gap-1.5">
            {hasPromo && <span className="text-[10px] text-neutral-400 line-through">{formatPrice(product.price)}</span>}
            <span className={`text-sm font-bold ${hasPromo ? 'text-red-600' : 'text-neutral-900'}`}>
              {formatPrice(price)}
            </span>
          </div>
          <div onClick={(e) => e.stopPropagation()}>
            <MiniCartButton code={product.code} size="sm" />
          </div>
        </div>
      </div>

      <button
        onClick={onToggle}
        className="flex-shrink-0 w-8 h-8 rounded-full hover:bg-red-50 flex items-center justify-center"
        aria-label="Remover dos favoritos"
      >
        <Heart className={`w-4 h-4 ${isFavorite ? 'fill-red-500 text-red-500' : 'text-neutral-300'}`} />
      </button>
    </div>
  )
}
