<script setup lang="ts">
import { ref, onBeforeMount, computed, defineAsyncComponent } from "vue";
import type { Task } from "@/types";
import { getTasks, createTask, deleteTask } from "@/api/tasks";
import { CirclePlus } 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";

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));

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

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

function onNewTask() {
    if (taskInput.value.trim()) {
        void createTask(list.value, {
            name: taskInput.value.trim(),
            reset_cron: null,
        })
            .then((data: Task) => {
                tasks.value.push(data);
                reSortTasks();
            })
            .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);
}

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">
            {{ $t('empty_hint') }}
        </li>
        <li v-if="allCompleted && separateCompleted" class="list-row italic text-xl font-extralight">
            {{ $t('all_completed_hint') }}
        </li>
        <li class="list-row">
            <div class="list-col-grow">
                <input
                    v-model="taskInput"
                    type="text"
                    :placeholder="$t('new_task_hint')"
                    class="input"
                    @keyup.enter="onNewTask"
                />
            </div>
            <div>
                <button
                    class="btn btn-square"
                    :disabled="taskInput.trim().length === 0"
                    @click="onNewTask"
                >
                    <CirclePlus />
                </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">{{ $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">{{ $t('options.title') }}</div>
      <div class="collapse-content text-sm">
          <fieldset class="fieldset flex flex-col gap-2">
              <label class="label">
                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>
