import { useSearchParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Sparkles } from 'lucide-react'
import { aiNlSearch } from '../api/client'
import ProductCard from './components/ProductCard'

export default function Search() {
  const { t } = useTranslation()
  const [sp] = useSearchParams()
  const q = sp.get('q') || ''
  const { data, isLoading } = useQuery({
    queryKey: ['nl-search', q],
    queryFn: () => aiNlSearch(q),
    enabled: !!q,
  })
  const items = data?.items || []

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-2">
        <Sparkles className="text-bloom" size={20} />
        <h1 className="font-serif text-2xl font-bold">{t('search.resultsFor', { query: q })}</h1>
      </div>
      {data?.parsed && (
        <div className="text-xs text-bloom2 mb-5">{t('search.aiUnderstood')} <span className="font-medium">{JSON.stringify(data.parsed)}</span> · {data.source}</div>
      )}
      {isLoading && <div className="text-gray-400 py-10 text-center">{t('search.searching')}</div>}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {items.map((p: any) => <ProductCard key={p.id} p={p} />)}
      </div>
      {!isLoading && !items.length && <div className="text-center text-gray-400 py-16">{t('search.noResults')}</div>}
    </div>
  )
}
