import React, { useState, useEffect } from 'react';
import CalendarGrid from './components/CalendarGrid';
import TaskForm from './components/TaskForm';
import { Task } from './types/task';
import { loadTasks, saveTasks } from './lib/taskPersistence';

const App: React.FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [editingTask, setEditingTask] = useState<Task | null>(null);
  const [currentDate, setCurrentDate] = useState<Date>(new Date());

  useEffect(() => {
    // Load tasks from storage on mount
    const loadedTasks = loadTasks();
    setTasks(loadedTasks);
  }, []);

  const handleSaveTask = (task: Task) => {
    let updatedTasks;
    
    if (task.id) {
      // Update existing task
      updatedTasks = tasks.map(t => t.id === task.id ? task : t);
    } else {
      // Add new task
      updatedTasks = [...tasks, task];
    }
    
    setTasks(updatedTasks);
    saveTasks(updatedTasks);
    setShowForm(false);
    setEditingTask(null);
  };

  const handleCancelForm = () => {
    setShowForm(false);
    setEditingTask(null);
  };

  const handleToggleComplete = (id: string) => {
    const updatedTasks = tasks.map(task => 
      task.id === id ? { ...task, completed: !task.completed } : task
    );
    setTasks(updatedTasks);
    saveTasks(updatedTasks);
  };

  const handleEditTask = (task: Task) => {
    setEditingTask(task);
    setShowForm(true);
  };

  const handleDeleteTask = (id: string) => {
    const updatedTasks = tasks.filter(task => task.id !== id);
    setTasks(updatedTasks);
    saveTasks(updatedTasks);
  };

  const handleAddTask = (date: Date) => {
    setEditingTask({
      id: '',
      title: '',
      date,
      completed: false
    });
    setShowForm(true);
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-6xl mx-auto">
        <header className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">Weekly ToDo List</h1>
          <p className="text-gray-600">Manage your tasks with advanced features</p>
        </header>

        <main>
          <CalendarGrid
            tasks={tasks}
            onTaskToggle={handleToggleComplete}
            onTaskEdit={handleEditTask}
            onTaskDelete={handleDeleteTask}
            onAddTask={handleAddTask}
            currentDate={currentDate}
          />
        </main>

        {showForm && (
          <TaskForm
            task={editingTask}
            onSave={handleSaveTask}
            onCancel={handleCancelForm}
          />
        )}
      </div>
    </div>
  );
};

export default App;