import { useCallback, useEffect, useState } from "react";
import type { Task } from "../types/task";
import { nanoid } from "nanoid";

export const useTasks = () => {
    const [tasks, setTasks] = useState<Task[]>(() => {
        const savedTasks = localStorage.getItem('tasks');
        return savedTasks ? JSON.parse(savedTasks) : []
    });

    useEffect(() => {
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }, [tasks]);

    const addTask = (title: string) => {
        if (title.trim() === '') return;

        const newTask: Task = {
            id: nanoid(),
            title,
            completed: false,
            createdAt: new Date().toISOString()
        };
        
        setTasks(prev => [...prev, newTask]);
    };

    const deleteTask = useCallback((id: string) => {
        setTasks(prev => prev.filter(task => task.id !== id));
    }, []);

    const toggleTask = useCallback((id: string) => {
        setTasks(prev => prev.map(task =>
            task.id === id ? { ...task, completed: !task.completed } : task
        ));
    }, []);

    return { tasks, addTask, deleteTask, toggleTask };
};