import { create } from "zustand"
import api from "../service/api"
import { toast } from "react-hot-toast"
const useTaskStore = create((set) => ({
    tasks: [],
    fetchTasks: async () => {
        try{
            const res = await api.get("/task")
            if(res.status === 200){
                set({ tasks: res.data.tasks })
            }
        }catch(error){
            console.log(error)
        }
    },
    addTask: async(title, completed) => {
        try {
            const res = await api.post("/task/add", { title, completed })
            if(res.status === 201){
                set((state) => ({ tasks: [...state.tasks, res.data.task] }))
                toast.success(res.data.message)
            } else {
                toast.error(res?.data?.message || "something went wrong")
            }
        } catch (error) {
            console.log(error)
            toast.error(error?.response?.data?.message || "server error")
        }
    },
    deleteTask: async(id) => {
        try {
            const res = await api.delete(`/task/delete/${id}`)
            if(res.status === 200){
                set((state) => ({ tasks: state.tasks.filter(task => task._id !== id) }))
                toast.success(res.data.message)
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    },
    updateTask: async(id, title, completed) => {
        try {
            const res = await api.put(`/task/update/${id}`, { title, completed })
            if(res.status === 200){
                set((state) => ({ tasks: state.tasks.map(task => task._id === id ? { ...task, title, completed } : task) }))
                toast.success(res.data.message)
            }else{
                toast.error(res.data.message)
            }
        } catch (error) {
            console.log(error)
        }
    }
}))

export default useTaskStore