<script setup lang="ts">
import { ref, onBeforeMount } from "vue";
import type { Task } from "@/types";
import { getTasks, createTask } 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 newTask() {
    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 = "";
            });
    }
}

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]" />
        </li>
        <li class="list-row">
            <div class="list-col-grow">
                <input
                    v-model="taskInput"
                    type="text"
                    placeholder="New Task"
                    class="input"
                    @keyup.enter="newTask"
                />
            </div>
            <div>
                <button
                    class="btn btn-square"
                    :disabled="taskInput.trim().length === 0"
                    @click="newTask"
                >
                    <CirclePlus />
                </button>
            </div>
        </li>
    </ul>
</template>
