import { useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { Sparkles, SlidersHorizontal, Flower2 } from 'lucide-react'
import { getProducts, aiNlSearch, getCategories } from '../api/client'
import ProductCard from './components/ProductCard'
import { Reveal, StaggerGrid, StaggerItem } from './components/motion'

const OCCASIONS: [string, string][] = [
  ['', 'All'], ['BIRTHDAY', 'Birthday'], ['ANNIVERSARY', 'Anniversary'],
  ['SYMPATHY', 'Sympathy'], ['CONGRATS', 'Congrats'], ['ROMANCE', 'Romance'],
]
const SORTS = [['', 'Recommended'], ['price_asc', 'Price ↑'], ['price_desc', 'Price ↓'], ['sales', 'Bestselling'], ['rating', 'Top rated']]

export default function Category() {
  const [sp, setSp] = useSearchParams()
  const occasion = sp.get('occasion') || ''
  const [sort, setSort] = useState(sp.get('sort') || '')
  const [maxPrice, setMaxPrice] = useState('')
  const [nl, setNl] = useState('')
  const [nlResult, setNlResult] = useState<any>(null)

  useQuery({ queryKey: ['cats'], queryFn: getCategories })
  const { data } = useQuery({
    queryKey: ['products', occasion, sort, maxPrice],
    queryFn: () => getProducts({ occasion, sort, maxPrice: maxPrice ? Number(maxPrice) : undefined, size: 24 }),
  })
  const items = nlResult ? nlResult.items : (data?.items || [])

  const setOccasion = (o: string) => { const n = new URLSearchParams(sp); if (o) n.set('occasion', o); else n.delete('occasion'); setSp(n); setNlResult(null) }
  const runNl = async (e: React.FormEvent) => {
    e.preventDefault(); if (!nl.trim()) { setNlResult(null); return }
    const r = await aiNlSearch(nl.trim()).catch(() => null)
    setNlResult(r)
  }

  const title = OCCASIONS.find(o => o[0] === occasion)?.[1] || 'All'

  return (
    <div>
      {/* 카테고리 헤더 배너 */}
      <section className="bg-gradient-to-br from-blush-50 to-ivory border-b border-blush-100">
        <div className="max-w-6xl mx-auto px-4 py-10">
          <div className="text-[12px] tracking-[0.2em] uppercase text-sage-600 mb-2">Shop the collection</div>
          <h1 className="font-serif text-4xl text-blush-900">{title === 'All' ? 'All Flowers' : title}</h1>
        </div>
      </section>

      <div className="max-w-6xl mx-auto px-4 py-8">
        <form onSubmit={runNl} className="flex items-center gap-2 bg-white border border-blush-100 rounded-full px-5 py-3 mb-6 max-w-xl shadow-soft">
          <Sparkles size={16} className="text-blush-500" />
          <input value={nl} onChange={e => setNl(e.target.value)} placeholder='Try "anniversary roses under $80"'
            className="flex-1 text-sm outline-none bg-transparent placeholder:text-blush-300" />
          <button className="text-blush-500 text-sm font-semibold">AI Search</button>
        </form>
        {nlResult && <div className="text-xs text-sage-700 mb-4">AI understood: <span className="font-medium">{JSON.stringify(nlResult.parsed)}</span> · {nlResult.source}</div>}

        <div className="flex flex-wrap items-center gap-2 mb-7">
          {OCCASIONS.map(([o, label]) => (
            <button key={o} onClick={() => setOccasion(o)}
              className={`px-4 py-1.5 rounded-full text-sm border transition-colors ${occasion === o ? 'bg-blush-500 text-white border-blush-500' : 'bg-white text-[#6b5258] border-blush-100 hover:border-blush-300'}`}>
              {label}
            </button>
          ))}
          <div className="ml-auto flex items-center gap-2">
            <SlidersHorizontal size={15} className="text-blush-300" />
            <input value={maxPrice} onChange={e => { setMaxPrice(e.target.value.replace(/\D/g, '')); setNlResult(null) }} placeholder="Max $"
              className="w-24 px-3 py-1.5 rounded-full border border-blush-100 text-sm outline-none focus:border-blush-300" />
            <select value={sort} onChange={e => { setSort(e.target.value); setNlResult(null) }}
              className="px-3 py-1.5 rounded-full border border-blush-100 text-sm outline-none bg-white">
              {SORTS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
            </select>
          </div>
        </div>

        <StaggerGrid className="grid grid-cols-2 md:grid-cols-4 gap-5">
          {items.map((p: any) => <StaggerItem key={p.id}><ProductCard p={p} /></StaggerItem>)}
        </StaggerGrid>
        {!items.length && (
          <Reveal className="text-center text-blush-300 py-20">
            <Flower2 size={40} className="mx-auto mb-3 text-blush-200" />
            No flowers match those filters.
          </Reveal>
        )}
      </div>
    </div>
  )
}
