<script setup lang="ts">
import { ref, onBeforeMount, computed, defineAsyncComponent } from "vue";
import type { Task } from "@/types";
import { getTasks, createTask, deleteTask } from "@/api/tasks";
import { CirclePlusIcon, ArrowDownUpIcon, Settings2Icon, CircleCheckBigIcon, CheckCheckIcon, SearchIcon } from "@lucide/vue";
const TaskItem = defineAsyncComponent(
    () => import("@/components/TaskItem.vue"),
);
import { taskCompleted, sortTasks } from "@/lib/tasks";
import { SortType } from "@/enums";
import { booleanCookieRef, enumCookieRef } from "@/lib/cookies";
import { useAlertStore } from "@/stores/alerts";
import { useI18n } from "vue-i18n";

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

const sortType = enumCookieRef<SortType>(
    "toutDouxSortType",
    SortType.CREATED_AT,
);
const sortReverse = booleanCookieRef("toutDouxSortReverse", false);
const showLastChecked = booleanCookieRef("toutDouxShowLastChecked", false);
const showNextReset = booleanCookieRef("toutDouxShowNextReset", false);
const separateCompleted = booleanCookieRef("toutDouxSeparateCompleted", false);

const hasCompleted = computed<boolean>(() => tasks.value.some(taskCompleted));
const empty = computed<boolean>(() => tasks.value.length === 0);
const allCompleted = computed<boolean>(() => tasks.value.every(taskCompleted));

const i18n = useI18n();

const { alertSuccess, alertError, alertWarning } = useAlertStore();

function fetchTasks() {
    getTasks(list.value)
        .then((data: Task[]) => {
            tasks.value = data;
            reSortTasks();
            setTimeout(fetchTasks, 10000);
        })
        .catch(() => {
            if (tasks.value.length !== 0) {
                alertWarning(i18n.t("alerts.task_refresh_error"));
            } else {
                alertError(i18n.t("alerts.task_fetch_error"));
            }
        });
}

function reSortTasks() {
    tasks.value = sortTasks(tasks.value, sortType.value, sortReverse.value);
}

function onNewTask() {
    if (taskInput.value.trim()) {
        createTask(list.value, {
            name: taskInput.value.trim(),
            reset_cron: null,
        })
            .then((data: Task) => {
                tasks.value.push(data);
                reSortTasks();
                alertSuccess(i18n.t("alerts.task_created"));
            })
            .catch(() => {
                alertError(i18n.t("alerts.task_create_error"));
            })
            .finally(() => {
                taskInput.value = "";
            });
    }
}

function onCloneTask(task: Task) {
    createTask(list.value, {
        name: task.name,
        reset_cron: task.reset_cron,
    })
        .then((data: Task) => {
            tasks.value.push(data);
            alertSuccess(i18n.t("alerts.task_cloned"));
        })
        .catch(() => {
            alertError(i18n.t("alerts.task_create_error"));
        });
}

function onDeleteTask(task: Task) {
    deleteTask(task.id)
        .then(() => {
            alertSuccess(i18n.t("alerts.task_deleted"));
        })
        .catch(() => {
            alertError(i18n.t("alerts.task_delete_error"));
        });

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

function onChangeSortType() {
    reSortTasks();
}

function onChangeSortReverse() {
    reSortTasks();
}

onBeforeMount(fetchTasks);
</script>

<template>
    <ul class="list">
        <template v-for="(task, i) in tasks" :key="task.id">
            <li v-if="tasks[i] && (!separateCompleted || !taskCompleted(task))">
                <task-item
                    v-model="tasks[i]"
                    :show-last-checked="showLastChecked"
                    :show-next-reset="showNextReset"
                    @clone="onCloneTask"
                    @delete="onDeleteTask"
                />
            </li>
        </template>
        <li v-if="empty" class="list-row italic text-xl font-extralight self-center">
            <span><search-icon class="inline" /> <span v-html="$t('empty_hint')"></span></span>
        </li>
        <li
            v-else-if="allCompleted && separateCompleted"
            class="list-row italic text-xl font-extralight self-center"
        >
            <span><check-check-icon class="inline" /> <span v-html="$t('all_completed_hint')"></span></span>
        </li>
        <li class="list-row">
            <div class="list-col-grow">
                <input
                    v-model="taskInput"
                    type="text"
                    :placeholder="$t('new_task_hint')"
                    class="input w-full"
                    @keyup.enter="onNewTask"
                />
            </div>
            <div>
                <button
                    class="btn btn-square"
                    :disabled="taskInput.trim().length === 0"
                    @click="onNewTask"
                >
                    <circle-plus-icon />
                </button>
            </div>
        </li>
    </ul>
    <div
        v-if="separateCompleted && hasCompleted"
        class="collapse collapse-arrow"
    >
        <input id="completed-dropdown" type="checkbox" />
        <div class="collapse-title mb-0"><circle-check-big-icon class="inline" :size="24" /> {{ $t("completed") }}</div>
        <div class="collapse-content p-0">
            <ul class="list">
                <template
                    v-for="(task, i) in tasks"
                    :key="`${task.id}-completed`"
                >
                    <li v-if="tasks[i] && taskCompleted(task)">
                        <task-item
                            v-model="tasks[i]"
                            :show-last-checked="showLastChecked"
                            :show-next-reset="showNextReset"
                            @clone="onCloneTask"
                            @delete="onDeleteTask"
                        />
                    </li>
                </template>
            </ul>
        </div>
    </div>
    <div class="collapse collapse-arrow font-light text-sm">
        <input id="options-dropdown" type="checkbox" />
        <div class="collapse-title"><settings-2-icon class="inline" :size="16" /> {{ $t("options.title") }}</div>
        <div class="collapse-content">
            <fieldset class="fieldset flex flex-col gap-2">
                <label class="label">
                    <arrow-down-up-icon class="inline" /> {{ $t("options.sort_by") }}
                    <select
                        v-model="sortType"
                        class="select"
                        @change="onChangeSortType"
                    >
                        <option :value="SortType.CREATED_AT">
                            {{ $t("options.sort.created_at") }}
                        </option>
                        <option :value="SortType.UPDATED_AT">
                            {{ $t("options.sort.updated_at") }}
                        </option>
                        <option :value="SortType.CHECK_DATE">
                            {{ $t("options.sort.check_date") }}
                        </option>
                        <option :value="SortType.RESET_DATE">
                            {{ $t("options.sort.reset_date") }}
                        </option>
                        <option :value="SortType.NAME">
                            {{ $t("options.sort.name") }}
                        </option>
                    </select>
                </label>
                <label class="label">
                    <input
                        v-model="sortReverse"
                        type="checkbox"
                        class="checkbox"
                        @change="onChangeSortReverse"
                    />
                    {{ $t("options.reverse_sort") }}
                </label>
                <label class="label">
                    <input
                        v-model="showLastChecked"
                        type="checkbox"
                        class="checkbox"
                    />
                    {{ $t("options.last_checked") }}
                </label>
                <label class="label">
                    <input
                        v-model="showNextReset"
                        type="checkbox"
                        class="checkbox"
                    />
                    {{ $t("options.next_reset") }}
                </label>
                <label class="label">
                    <input
                        v-model="separateCompleted"
                        type="checkbox"
                        class="checkbox"
                    />
                    {{ $t("options.separate_completed") }}
                </label>
            </fieldset>
        </div>
    </div>
</template>
