'use client'

import { motion, AnimatePresence } from 'framer-motion'
import { Search, X, Zap, TrendingDown, Star, Package } from 'lucide-react'
import { useCatalogStore } from '@/lib/store'
import { useEffect, useState, useRef } from 'react'
import type { Product } from '@/lib/types'
import { formatPrice, getEffectivePrice, getCategorySymbol } from '@/lib/catalog-utils'
import { fetchCategories } from '@/lib/categories-cache'
import { MiniCartButton } from './mini-cart-button'

const QUICK_FILTERS = [
  { key: 'launch', label: 'Lançamentos', icon: <Zap className="w-3.5 h-3.5" /> },
  { key: 'promo', label: 'Ofertas', icon: <TrendingDown className="w-3.5 h-3.5" /> },
  { key: 'bestseller', label: 'Mais Vendidos', icon: <Star className="w-3.5 h-3.5" /> },
  { key: 'lowerPrice', label: 'Menor Preço', icon: <Package className="w-3.5 h-3.5" /> },
] as const

export function SearchDrawer() {
  const { searchOpen, setSearchOpen, searchQuery, setSearchQuery, setSelectedProduct, goToPage } = useCatalogStore()
  const [results, setResults] = useState<Product[]>([])
  const [loading, setLoading] = useState(false)
  const [activeFilter, setActiveFilter] = useState<string | null>(null)
  const [category, setCategory] = useState<string>('all')
  const [categories, setCategories] = useState<{ id: string; name: string; slug: string }[]>([])
  const inputRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    fetchCategories()
      .then(setCategories)
      .catch(() => {})
  }, [])

  useEffect(() => {
    if (searchOpen) {
      setTimeout(() => inputRef.current?.focus(), 250)
    }
  }, [searchOpen])

  useEffect(() => {
    if (!searchOpen) return
    const params = new URLSearchParams()
    if (searchQuery) params.set('search', searchQuery)
    if (category !== 'all') params.set('category', category)
    if (activeFilter === 'launch') params.set('launch', 'true')
    if (activeFilter === 'promo') params.set('promo', 'true')
    if (activeFilter === 'bestseller') params.set('bestseller', 'true')
    if (activeFilter === 'lowerPrice') params.set('lowerPrice', 'true')
    params.set('limit', '100')

    let cancelled = false
    const t = setTimeout(() => {
      setLoading(true)
      fetch(`/api/products?${params.toString()}`)
        .then(r => r.json())
        .then(res => { if (!cancelled) setResults(res.data || []) })
        .catch(() => { if (!cancelled) setResults([]) })
        .finally(() => { if (!cancelled) setLoading(false) })
    }, 200)
    return () => { cancelled = true; clearTimeout(t) }
  }, [searchOpen, searchQuery, category, activeFilter])

  const openProduct = (p: Product) => {
    setSelectedProduct(p)
  }

  const jumpToPage = (page: number) => {
    goToPage(page)
    setSearchOpen(false)
  }

  return (
    <AnimatePresence>
      {searchOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setSearchOpen(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"
          >
            {/* Header */}
            <div className="flex-shrink-0 p-4 border-b border-neutral-100">
              <div className="flex items-center justify-between mb-3">
                <h2 className="text-base font-bold text-neutral-900 flex items-center gap-2">
                  <Search className="w-4 h-4 text-amber-500" />
                  Buscar produtos
                </h2>
                <button
                  onClick={() => setSearchOpen(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>

              {/* Search input */}
              <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-400" />
                <input
                  ref={inputRef}
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Nome, código, fragrância..."
                  className="w-full pl-10 pr-9 py-2.5 text-sm bg-neutral-50 border border-neutral-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-amber-400 focus:border-transparent"
                />
                {searchQuery && (
                  <button
                    onClick={() => setSearchQuery('')}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-neutral-400 hover:text-neutral-600"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>

              {/* Quick filters */}
              <div className="flex flex-wrap gap-1.5 mt-3">
                {QUICK_FILTERS.map(f => (
                  <button
                    key={f.key}
                    onClick={() => setActiveFilter(activeFilter === f.key ? null : f.key)}
                    className={`flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
                      activeFilter === f.key
                        ? 'bg-amber-400 text-black'
                        : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'
                    }`}
                  >
                    {f.icon} {f.label}
                  </button>
                ))}
              </div>

              {/* Category chips */}
              <div className="flex flex-wrap gap-1.5 mt-2">
                <button
                  onClick={() => setCategory('all')}
                  className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
                    category === 'all' ? 'bg-neutral-900 text-white' : 'bg-neutral-50 text-neutral-500 hover:bg-neutral-100'
                  }`}
                >
                  Todas
                </button>
                {categories.map(c => (
                  <button
                    key={c.id}
                    onClick={() => setCategory(category === c.slug ? 'all' : c.slug)}
                    className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
                      category === c.slug ? 'bg-neutral-900 text-white' : 'bg-neutral-50 text-neutral-500 hover:bg-neutral-100'
                    }`}
                  >
                    {c.name}
                  </button>
                ))}
              </div>
            </div>

            {/* Results */}
            <div className="flex-1 min-h-0 overflow-y-auto p-3">
              <div className="text-[11px] text-neutral-400 font-medium mb-2 px-1">
                {loading ? 'Buscando...' : `${results.length} produto${results.length !== 1 ? 's' : ''}`}
              </div>

              {loading ? (
                <div className="space-y-2">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <div key={i} className="h-16 bg-neutral-100 rounded-xl animate-pulse" />
                  ))}
                </div>
              ) : results.length === 0 ? (
                <div className="text-center py-12 text-neutral-400">
                  <Search className="w-10 h-10 mx-auto mb-3 opacity-30" />
                  <p className="text-sm">Nenhum produto encontrado</p>
                  <p className="text-xs mt-1">Tente outro termo ou filtro</p>
                </div>
              ) : (
                <div className="space-y-2">
                  {results.map(p => {
                    const price = getEffectivePrice(p)
                    const hasPromo = p.promotionalPrice && p.promotionalPrice < p.price
                    return (
                      <div
                        key={p.id}
                        className="group flex items-center gap-3 p-2.5 rounded-xl hover:bg-amber-50 transition-colors cursor-pointer border border-transparent hover:border-amber-100"
                        onClick={() => openProduct(p)}
                      >
                        {/* Thumbnail (page preview) */}
                        <button
                          onClick={(e) => { e.stopPropagation(); jumpToPage(p.page) }}
                          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 ${p.page}`}
                        >
                          <img
                            src={`/catalog-pages-thumbs/page-${String(p.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.{p.page}
                          </span>
                        </button>

                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-1.5 mb-0.5">
                            <span className="text-[10px] font-mono text-neutral-400">#{p.code}</span>
                            {p.isLaunch && <Tag color="bg-amber-100 text-amber-700">Novo</Tag>}
                            {hasPromo && p.discountPercent && <Tag color="bg-red-100 text-red-700">-{p.discountPercent}%</Tag>}
                          </div>
                          <h3 className="text-sm font-semibold text-neutral-900 leading-tight truncate group-hover:text-amber-700">
                            {p.name}
                          </h3>
                          <div className="flex items-center gap-1.5 mt-0.5">
                            {p.category && (
                              <span className="text-[10px] text-neutral-400 flex items-center gap-0.5">
                                {getCategorySymbol(p.category.slug)} {p.category.name}
                              </span>
                            )}
                          </div>
                          <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(p.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={p.code} size="sm" />
                            </div>
                          </div>
                        </div>
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          </motion.aside>
        </>
      )}
    </AnimatePresence>
  )
}

function Tag({ color, children }: { color: string; children: React.ReactNode }) {
  return (
    <span className={`text-[9px] font-bold px-1.5 py-0.5 rounded ${color}`}>{children}</span>
  )
}
