<script setup lang="ts">
import { ref, onMounted, 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 visible = ref<boolean>(false);
const taskInput = ref<string>("");
const tasks = ref<Task[]>([]);
const list = ref<string>("test");

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

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

onBeforeMount(fetchTasks);

onMounted(() => {
    setTimeout(() => {
        visible.value = true;
    });
});
</script>

<template>
    <main :style="{ display: visible ? 'inherit' : 'none' }">
        <div class="hero bg-base-200 min-h-screen">
            <div class="hero-content text-center">
                <div class="max-w-md min-w-96">
                    <ul class="list bg-base-100 rounded-box shadow-md">
                        <li
                            class="p-4 pb-2 text-4xl font-bold opacity-60 tracking-wide select-none"
                        >
                            Tout Doux
                        </li>

                        <li v-for="(task, i) in tasks" :key="task.id">
                            <TaskItem 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>
                </div>
            </div>
        </div>
    </main>
</template>
