import { useState, useEffect, useCallback } from 'react'
import { api } from '../api/client'
import type { Drink } from '../api/types'
import { DrinkCard } from '../components/DrinkCard'
import { SearchBar } from '../components/SearchBar'

export function Home() {
  const [drinks, setDrinks] = useState<Drink[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [category, setCategory] = useState<string | null>(null)

  const fetchDrinks = useCallback(async () => {
    setLoading(true)
    try {
      const data = await api.listDrinks({
        search: search || undefined,
        category: category || undefined,
      })
      setDrinks(data)
    } catch (err) {
      console.error('Erreur chargement:', err)
    } finally {
      setLoading(false)
    }
  }, [search, category])

  useEffect(() => {
    const debounce = setTimeout(fetchDrinks, 300)
    return () => clearTimeout(debounce)
  }, [fetchDrinks])

  return (
    <div className="space-y-6">
      <div>
        <h2 className="font-display text-3xl font-bold text-cellar-cream mb-1">
          Ma Cave
        </h2>
        <p className="text-cellar-muted">
          {drinks.length} boisson{drinks.length !== 1 ? 's' : ''} dans votre collection
        </p>
      </div>

      <SearchBar
        onSearch={setSearch}
        onCategoryChange={setCategory}
        activeCategory={category}
      />

      {loading ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
          {[...Array(8)].map((_, i) => (
            <div key={i} className="card animate-pulse">
              <div className="aspect-[3/4] bg-cellar-surface" />
              <div className="p-3 space-y-2">
                <div className="h-4 bg-cellar-surface rounded w-3/4" />
                <div className="h-3 bg-cellar-surface rounded w-1/2" />
              </div>
            </div>
          ))}
        </div>
      ) : drinks.length === 0 ? (
        <div className="text-center py-20">
          <div className="text-6xl mb-4 opacity-30">🍷</div>
          <h3 className="font-display text-xl text-cellar-muted mb-2">
            {search || category ? 'Aucun résultat' : 'Votre cave est vide'}
          </h3>
          <p className="text-cellar-muted text-sm">
            {search || category
              ? 'Essayez une autre recherche ou un autre filtre'
              : 'Commencez par ajouter votre première boisson'}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
          {drinks.map((drink) => (
            <DrinkCard key={drink.id} drink={drink} />
          ))}
        </div>
      )}
    </div>
  )
}
