'use client';

import React, { useState, useEffect, useCallback } from 'react';
import AddTodoForm from '@/components/AddTodoForm';
import TodoItem from '@/components/TodoItem';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

export default function Home() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  const fetchTodos = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch('/api/todos');
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      const data: Todo[] = await res.json();
      setTodos(data);
    } catch (e: any) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleAddTodo = async (title: string) => {
    try {
      const res = await fetch('/api/todos', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ title, completed: false }),
      });
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      await fetchTodos(); // Re-fetch todos to get the updated list with the new ID
    } catch (e: any) {
      setError(e.message);
    }
  };

  const handleToggleTodo = async (id: number) => {
    const todoToToggle = todos.find(todo => todo.id === id);
    if (!todoToToggle) return;

    try {
      const res = await fetch(`/api/todos/${id}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ completed: !todoToToggle.completed }),
        }
      );
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      await fetchTodos(); // Re-fetch todos to get the updated list
    } catch (e: any) {
      setError(e.message);
    }
  };

  const handleDeleteTodo = async (id: number) => {
    try {
      const res = await fetch(`/api/todos/${id}`,
        {
          method: 'DELETE',
        }
      );
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      await fetchTodos(); // Re-fetch todos to get the updated list
    } catch (e: any) {
      setError(e.message);
    }
  };

  if (loading) return <div className="flex justify-center items-center min-h-screen text-xl">Chargement des tâches...</div>;
  if (error) return <div className="flex justify-center items-center min-h-screen text-xl text-red-600">Erreur: {error}</div>;

  return (
    <div className="min-h-screen bg-gray-100 flex flex-col items-center justify-center py-10">
      <div className="w-full max-w-md bg-white p-6 rounded-lg shadow-lg">
        <h1 className="text-3xl font-bold text-center text-gray-800 mb-6">Ma Liste de Tâches</h1>
        <AddTodoForm onAdd={handleAddTodo} />
        {
          todos.length === 0 ? (
            <p className="text-center text-gray-500">Aucune tâche pour le moment. Ajoutez-en une !</p>
          ) : (
            <ul>
              {todos.map((todo) => (
                <TodoItem
                  key={todo.id}
                  todo={todo}
                  onToggle={handleToggleTodo}
                  onDelete={handleDeleteTodo}
                />
              ))}
            </ul>
          )
        }
      </div>
    </div>
  );
}