<script setup lang="ts">
import { ref, onBeforeMount } from "vue";
import type { Task } from "@/types";
import { getTasks, createTask, deleteTask } from "@/api/tasks";
import { CirclePlus } from "@lucide/vue";
import TaskItem from "@/components/TaskItem.vue";

const taskInput = ref<string>("");
const tasks = ref<Task[]>([]);
const list = ref<string>("test");

function fetchTasks() {
    void getTasks(list.value)
        .then((data: Task[]) => {
            tasks.value = data;
            setTimeout(fetchTasks, 10000);
        });
}

function onNewTask() {
    if (taskInput.value.trim()) {
        void createTask(list.value, {
            name: taskInput.value.trim(),
            reset_cron: null,
        })
            .then((data: Task) => {
                tasks.value.push(data);
            })
            .finally(() => {
                taskInput.value = "";
            });
    }
}

function onCloneTask(task: Task) {
    void createTask(list.value, {
        name: task.name,
        reset_cron: task.reset_cron,
    }).then((data: Task) => {
        tasks.value.push(data);
    })
}

function onDeleteTask(task: Task) {
    void deleteTask(task.id);

    tasks.value.splice(tasks.value.indexOf(task), 1);
}

onBeforeMount(fetchTasks);
</script>

<template>
    <ul class="list ">
        <li v-for="(task, i) in tasks" :key="task.id">
            <task-item v-if="tasks[i]" v-model="tasks[i]" @clone="onCloneTask" @delete="onDeleteTask" />
        </li>
        <li class="list-row">
            <div class="list-col-grow">
                <input
                    v-model="taskInput"
                    type="text"
                    placeholder="New Task"
                    class="input"
                    @keyup.enter="onNewTask"
                />
            </div>
            <div>
                <button
                    class="btn btn-square"
                    :disabled="taskInput.trim().length === 0"
                    @click="onNewTask"
                >
                    <CirclePlus />
                </button>
            </div>
        </li>
    </ul>
</template>
