import { useState } from 'react'
import { searchFoods } from '../utils/api'

export default function FoodSearch({ onSelect, onClose }) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [loading, setLoading] = useState(false)

  const handleSearch = async () => {
    if (!query.trim()) return
    setLoading(true)
    try {
      const data = await searchFoods(query)
      setResults(data)
    } catch (err) {
      console.error('Search failed', err)
    } finally {
      setLoading(false)
    }
  }

  const handleSelect = (item) => {
    onSelect({
      name: item.name || item.product?.product_name || item.product?.product_name_en || query,
      calories: Math.round(item.calories || item.product?.nutriments?.['energy-kcal_100g'] || 0),
      protein: Math.round(item.protein || item.product?.nutriments?.proteins_100g || 0),
      carbs: Math.round(item.carbs || item.product?.nutriments?.carbohydrates_100g || 0),
      fat: Math.round(item.fat || item.product?.nutriments?.fat_100g || 0)
    })
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg w-full max-w-md max-h-[80vh] flex flex-col">
        <div className="p-4 border-b flex items-center justify-between">
          <h2 className="font-semibold">Search Food</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl">&times;</button>
        </div>
        
        <div className="p-4 border-b flex gap-2">
          <input type="text" value={query} onChange={e => setQuery(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleSearch()} placeholder="Search OpenFoodFacts..." className="flex-1 px-3 py-2 border rounded-lg" />
          <button onClick={handleSearch} className="px-4 py-2 bg-emerald-600 text-white rounded-lg hover:bg-emerald-700">Search</button>
        </div>

        <div className="flex-1 overflow-y-auto p-4">
          {loading && <div className="text-center py-4 text-gray-500">Searching...</div>}
          {!loading && results.length === 0 && query && <div className="text-center py-4 text-gray-500">No results found</div>}
          {results.map(item => (
            <button key={item.code} onClick={() => handleSelect(item)} className="w-full text-left p-3 hover:bg-gray-50 rounded-lg border-b last:border-b-0">
              <div className="font-medium">{item.product?.product_name || item.product?.product_name_en || 'Unknown'}</div>
              <div className="text-xs text-gray-500">
                {item.product?.nutriments?.['energy-kcal_100g'] || '?'} kcal · 
                P: {item.product?.nutriments?.proteins_100g || '?'}g · 
                C: {item.product?.nutriments?.carbohydrates_100g || '?'}g · 
                F: {item.product?.nutriments?.fat_100g || '?'}g
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  )
}