import { useState, useEffect } from 'react';
import { api, Entry } from '../lib/api';
import EntryInput from '../components/EntryInput';
import EntryList from '../components/EntryList';

export default function Home() {
  const [entries, setEntries] = useState<Entry[]>([]);
  const [loading, setLoading] = useState(true);
  const [generating, setGenerating] = useState(false);

  const today = new Date().toISOString().split('T')[0];

  useEffect(() => {
    loadEntries();
  }, []);

  const loadEntries = async () => {
    setLoading(true);
    const res = await api.getDay(today);
    if (res.data) {
      setEntries(res.data.entries);
    }
    setLoading(false);
  };

  const handleAddEntry = async (type: string, content: string, metadata?: object) => {
    const res = await api.createEntry(today, type, content, metadata);
    if (res.data) {
      setEntries((prev) => [...prev, res.data!]);
    }
    return res;
  };

  const handleDeleteEntry = async (id: string) => {
    const res = await api.deleteEntry(id);
    if (res.data) {
      setEntries((prev) => prev.filter((e) => e.id !== id));
    }
  };

  const handleGenerateJournal = async () => {
    setGenerating(true);
    await api.generateJournal(today);
    setGenerating(false);
  };

  return (
    <div className="max-w-4xl mx-auto p-4">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Today</h1>
          <p className="text-slate-400">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })}</p>
        </div>
        <button
          onClick={handleGenerateJournal}
          disabled={generating || entries.length === 0}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 rounded-lg font-medium transition disabled:opacity-50"
        >
          {generating ? 'Generating...' : 'Generate Journal'}
        </button>
      </div>

      <EntryInput onSubmit={handleAddEntry} />

      {loading ? (
        <div className="text-center py-12 text-slate-400">Loading...</div>
      ) : entries.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-slate-400 mb-2">No entries yet today</p>
          <p className="text-slate-500 text-sm">Start capturing your day above</p>
        </div>
      ) : (
        <EntryList entries={entries} onDelete={handleDeleteEntry} />
      )}

      {entries.length > 0 && (
        <div className="mt-6 text-center">
          <a href={`/journal/${today}`} className="text-purple-400 hover:text-purple-300 text-sm">
            View journal →
          </a>
        </div>
      )}
    </div>
  );
}
