import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Layout from '../components/Layout';

export default function AddEntry() {
  const navigate = useNavigate();
  const [darkMode, setDarkMode] = useState(true);
  const [foods, setFoods] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [showSearch, setShowSearch] = useState(false);
  const [loading, setLoading] = useState(false);
  
  const [form, setForm] = useState({
    name: '',
    description: '',
    notes: '',
    calories: '',
    protein: '',
    carbs: '',
    fat: '',
    image: null
  });

  useEffect(() => {
    setDarkMode(document.documentElement.classList.contains('dark'));
  }, []);

  const bgCard = darkMode ? 'bg-gray-800' : 'bg-white';
  const textMain = darkMode ? 'text-white' : 'text-gray-900';
  const textMuted = darkMode ? 'text-gray-400' : 'text-gray-500';
  const inputBg = darkMode ? 'bg-gray-700 border-gray-600 text-white' : 'bg-white border-gray-300 text-gray-900';

  async function handleSearch() {
    if (!searchQuery) return;
    setLoading(true);
    try {
      const res = await fetch('/api/foods/search?q=' + searchQuery);
      const data = await res.json();
      if (Array.isArray(data)) {
        setFoods(data);
        setShowSearch(true);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }

  function selectFood(food) {
    setForm({
      ...form,
      name: food.name,
      calories: Math.round(food.calories),
      protein: Math.round(food.protein),
      carbs: Math.round(food.carbs),
      fat: Math.round(food.fat)
    });
    setShowSearch(false);
  }

  function handleSubmit(e) {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append('name', form.name);
    formData.append('description', form.description);
    formData.append('notes', form.notes);
    formData.append('calories', form.calories);
    formData.append('protein', form.protein);
    formData.append('carbs', form.carbs);
    formData.append('fat', form.fat);
    if (form.image) {
      formData.append('image', form.image);
    }

    fetch('/api/entries', {
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      navigate('/');
    })
    .catch(err => {
      console.error(err);
      alert('Failed to save entry');
    });
  }

  return (
    <Layout>
      <h1 className={"text-2xl font-bold mb-4 " + textMain}>Add Entry</h1>
      
      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Food Search */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Search Food (optional)</label>
          <div className="flex gap-2">
            <input
              type="text"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search food..."
              className={"flex-1 px-3 py-2 rounded-lg border " + inputBg}
            />
            <button type="button" onClick={handleSearch} className="bg-emerald-500 text-white px-4 py-2 rounded-lg">
              Search
            </button>
          </div>
          
          {showSearch && (
            <div className="mt-3 max-h-40 overflow-y-auto">
              {foods.length === 0 ? (
                <p className={textMuted}>No results found</p>
              ) : (
                foods.map((food, i) => (
                  <button
                    key={i}
                    type="button"
                    onClick={() => selectFood(food)}
                    className={"w-full text-left p-2 rounded hover:bg-gray-700 " + textMuted}
                  >
                    {food.name} • {food.calories}cal P:{food.protein}g C:{food.carbs}g F:{food.fat}g
                  </button>
                ))
              )}
            </div>
          )}
        </div>

        {/* Name */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Food Name *</label>
          <input
            type="text"
            required
            value={form.name}
            onChange={e => setForm({...form, name: e.target.value})}
            placeholder="e.g., Grilled Chicken"
            className={"w-full px-3 py-2 rounded-lg border " + inputBg}
          />
        </div>

        {/* Description */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Description</label>
          <input
            type="text"
            value={form.description}
            onChange={e => setForm({...form, description: e.target.value})}
            placeholder="e.g., Lunch"
            className={"w-full px-3 py-2 rounded-lg border " + inputBg}
          />
        </div>

        {/* Macros */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Macros</label>
          <div className="grid grid-cols-4 gap-2">
            <div>
              <label className={"block text-xs " + textMuted}>Calories</label>
              <input type="number" value={form.calories} onChange={e => setForm({...form, calories: e.target.value})} className={"w-full px-2 py-1 rounded border " + inputBg} />
            </div>
            <div>
              <label className={"block text-xs " + textMuted}>Protein</label>
              <input type="number" value={form.protein} onChange={e => setForm({...form, protein: e.target.value})} className={"w-full px-2 py-1 rounded border " + inputBg} />
            </div>
            <div>
              <label className={"block text-xs " + textMuted}>Carbs</label>
              <input type="number" value={form.carbs} onChange={e => setForm({...form, carbs: e.target.value})} className={"w-full px-2 py-1 rounded border " + inputBg} />
            </div>
            <div>
              <label className={"block text-xs " + textMuted}>Fat</label>
              <input type="number" value={form.fat} onChange={e => setForm({...form, fat: e.target.value})} className={"w-full px-2 py-1 rounded border " + inputBg} />
            </div>
          </div>
        </div>

        {/* Image */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Photo</label>
          <input
            type="file"
            accept="image/*"
            onChange={e => setForm({...form, image: e.target.files[0]})}
            className={"w-full " + textMuted}
          />
        </div>

        {/* Notes */}
        <div className={bgCard + " rounded-xl shadow-md p-4"}>
          <label className={"block text-sm font-medium mb-2 " + textMain}>Notes</label>
          <textarea
            value={form.notes}
            onChange={e => setForm({...form, notes: e.target.value})}
            placeholder="Any notes..."
            rows={3}
            className={"w-full px-3 py-2 rounded-lg border " + inputBg}
          />
        </div>

        {/* Submit */}
        <button type="submit" className="w-full bg-emerald-500 hover:bg-emerald-600 text-white py-3 rounded-xl font-semibold">
          Save Entry
        </button>
      </form>
    </Layout>
  );
}
