import React, { useEffect, useState } from 'react';
import { Todo } from './types';
import { fetchTodos, createTodo, updateTodo, deleteTodo } from './api/todo';
import TodoList from './components/TodoList';
import AddTodo from './components/AddTodo';
import './App.css';

const App: React.FC = () => {
  const [todos, setTodos] = useState<Todo[]>([]);

  const loadTodos = async () => {
    const data = await fetchTodos();
    setTodos(data);
  };

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

  const handleAdd = async (title: string) => {
    const newTodo = await createTodo({ title });
    setTodos((prev) => [...prev, newTodo]);
  };

  const handleToggle = async (id: number, completed: boolean) => {
    const updated = await updateTodo(id, { completed: !completed });
    setTodos((prev) => prev.map((t) => (t.id === id ? updated : t)));
  };

  const handleDelete = async (id: number) => {
    await deleteTodo(id);
    setTodos((prev) => prev.filter((t) => t.id !== id));
  };

  return (
    <div className="app">
      <h1>Todo List</h1>
      <AddTodo onAdd={handleAdd} />
      <TodoList todos={todos} onToggle={handleToggle} onDelete={handleDelete} />
    </div>
  );
};

export default App;
