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

export default function Daily() {
  const [entries, setEntries] = useState([]);
  const [summary, setSummary] = useState({ total_calories: 0, total_protein: 0, total_carbs: 0, total_fat: 0 });
  const [loading, setLoading] = useState(true);
  const [selectedDate, setSelectedDate] = useState(new Date().toISOString().split('T')[0]);
  const [isCurrentDay, setIsCurrentDay] = useState(true);
  const [darkMode, setDarkMode] = useState(true);

  useEffect(() => {
    loadData();
  }, [selectedDate]);

  useEffect(() => {
    const today = new Date().toISOString().split('T')[0];
    setIsCurrentDay(selectedDate === today);
    setDarkMode(document.documentElement.classList.contains('dark'));
  }, [selectedDate]);

  async function loadData() {
    try {
      setLoading(true);
      const entriesRes = await fetch('/api/entries?date=' + selectedDate);
      const entriesData = await entriesRes.json();
      const summaryRes = await fetch('/api/summary/daily?date=' + selectedDate);
      const summaryData = await summaryRes.json();
      setEntries(entriesData);
      setSummary(summaryData);
    } catch (err) {
      console.error('Failed to load:', err);
    } finally {
      setLoading(false);
    }
  }

  function formatDate(dateStr) {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
  }

  function handleDateChange(e) {
    setSelectedDate(e.target.value);
  }

  function goToToday() {
    setSelectedDate(new Date().toISOString().split('T')[0]);
  }

  function toggleTheme() {
    setDarkMode(!darkMode);
    if (darkMode) {
      document.documentElement.classList.remove('dark');
    } else {
      document.documentElement.classList.add('dark');
    }
  }

  const bgMain = darkMode ? 'bg-gray-900' : 'bg-gray-100';
  const bgCard = darkMode ? 'bg-gray-800' : 'bg-white';
  const bgSummary = darkMode ? 'bg-emerald-700' : 'bg-emerald-600';
  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';

  if (loading) return <Layout><div className="p-4">Loading...</div></Layout>;

  return (
    <Layout>
      <h1 className={"text-2xl font-bold mb-2 " + textMain}>
        {isCurrentDay ? "Today's Meals" : formatDate(selectedDate)}
      </h1>
      
      {/* Summary Card */}
      <div className={bgSummary + " text-white p-4 rounded-xl mb-4 shadow-lg"}>
        <div className="grid grid-cols-4 gap-2 text-center">
          <div>
            <div className="text-xs opacity-80">Cal</div>
            <div className="font-bold text-lg">{summary.total_calories || 0}</div>
          </div>
          <div>
            <div className="text-xs opacity-80">Protein</div>
            <div className="font-bold text-lg">{summary.total_protein || 0}g</div>
          </div>
          <div>
            <div className="text-xs opacity-80">Carbs</div>
            <div className="font-bold text-lg">{summary.total_carbs || 0}g</div>
          </div>
          <div>
            <div className="text-xs opacity-80">Fat</div>
            <div className="font-bold text-lg">{summary.total_fat || 0}g</div>
          </div>
        </div>
      </div>

      {/* Entries List */}
      <div className="space-y-3 mb-20">
        {entries.length === 0 ? (
          <div className={bgCard + " rounded-xl p-8 text-center " + textMuted}>
            <div className="text-4xl mb-2">🍽️</div>
            <p>No meals logged for this day</p>
          </div>
        ) : (
          entries.map(entry => (
            <Link 
              key={entry.id} 
              to={'/entry/' + entry.id + '?date=' + selectedDate} 
              className={bgCard + " rounded-xl shadow-md p-3 block hover:shadow-lg transition-shadow"}
            >
              <div className="flex gap-3">
                {entry.image_url && (
                  <img 
                    src={'http://10.10.10.143:3000' + entry.image_url} 
                    alt="" 
                    className="w-16 h-16 object-cover rounded-lg flex-shrink-0" 
                  />
                )}
                <div className="flex-1">
                  <div className={"font-semibold " + textMain}>{entry.name}</div>
                  {entry.description && <div className={"text-sm " + textMuted}>{entry.description}</div>}
                  <div className={"text-xs mt-1 " + textMuted}>
                    {entry.calories || 0} cal • P: {entry.protein || 0}g • C: {entry.carbs || 0}g • F: {entry.fat || 0}g
                  </div>
                </div>
              </div>
            </Link>
          ))
        )}
      </div>

      {/* Add Button */}
      {isCurrentDay && (
        <Link to="/add" className="fixed bottom-6 right-6 bg-emerald-500 hover:bg-emerald-600 text-white w-14 h-14 rounded-full flex items-center justify-center text-2xl shadow-xl">
          +
        </Link>
      )}
    </Layout>
  );
}
