<script setup lang="ts">
import { onBeforeMount, ref, watch, computed, defineAsyncComponent } from "vue";
import type { Task } from "@/types";
import { Copy, Trash, Save, X } from "@lucide/vue";
import { updateTask } from "@/api/tasks";
const CronInput = defineAsyncComponent(() => import("@/components/CronInput.vue"));
import { taskCompleted, taskNextReset } from "@/lib/tasks";
import { relativeTime } from "@/lib/dates";
import { useAlertStore } from "@/stores/alerts";
import { useI18n } from "vue-i18n";

const emit = defineEmits<(e: 'clone' | 'delete', task: Task) => void>();

const task = defineModel<Task>({ required: true });
defineProps<{ showLastChecked: boolean; showNextReset: boolean }>();

const editMode = ref<boolean>(false);
const editName = ref<string>('');
const editCron = ref<string|null>(null);
const refreshKey = ref<number>(0);

const checked = computed<boolean>(() => taskCompleted(task.value));
const nextReset = computed<Date | null>(() => taskNextReset(task.value));

const i18n = useI18n();

const { alertSuccess, alertError } = useAlertStore();

function onClose() {
    editMode.value = false;
}

function onSave() {
    updateTask(task.value.id, { name: editName.value, reset_cron: editCron.value })
        .then((newTask) => {
            task.value = newTask;
            alertSuccess(i18n.t('alerts.task_updated'));
        }).catch(() => {
            alertError(i18n.t('alerts.task_update_error'))
        })
    task.value.name = editName.value;
    task.value.reset_cron = editCron.value;
    editMode.value = false;
}

function onCheck() {
    if (!checked.value) {
        updateTask(task.value.id, { check_date: (new Date()).toISOString(), previous_check_date: task.value.check_date?.toISOString() })
            .then((newTask) => {
                task.value = newTask;
            }).catch(() => {
                alertError(i18n.t('alerts.task_update_error'))
            });
    } else {
        updateTask(task.value.id, { check_date: null, previous_check_date: task.value.check_date?.toISOString() })
            .then((newTask) => {
                task.value = newTask;
            }).catch(() => {
                alertError(i18n.t('alerts.task_update_error'))
            });
    }
}

function onClone() {
    emit('clone', task.value);
}

function onDelete() {
    emit('delete', task.value);
}

onBeforeMount(() => {
    editName.value = task.value.name;
    editCron.value = task.value.reset_cron;
    setInterval(() => {
        refreshKey.value++;
    }, 60000);
});
watch(task, () => {
    if (!editMode.value && task.value.name !== editName.value) {
        editName.value = task.value.name;
    }
    if (!editMode.value && task.value.reset_cron !== editCron.value) {
        editCron.value = task.value.reset_cron;
    }
});
</script>

<template>
    <div class="list-row text-left">
        <div class="content-center">
            <input :id="refreshKey.toFixed(0)" type="checkbox" class="checkbox" :checked="checked" @click.prevent="onCheck" />
        </div>
        <div
            v-if="!editMode"
            class="cursor-pointer text-lg select-none"
            @click.prevent="editMode = true"
        >
            <div>{{ task.name }}</div>
            <div v-if="showLastChecked && !checked && task.check_date" class="font-light text-xs italic">
                {{ $t('checked') }} {{ relativeTime(task.check_date, $i18n.locale) }}
            </div>
            <div v-if="showNextReset && checked && nextReset" class="font-light text-xs italic">
                {{ $t('resets') }} {{ relativeTime(nextReset, $i18n.locale) }}
            </div>
        </div>
        <template v-else>
            <div class="flex flex-col gap-2">
                <div class="flex justify-evenly">
                    <button class="btn btn-square me-1" @click="onClose">
                        <X />
                    </button>
                    <button class="btn btn-square me-1" @click="onSave">
                        <Save />
                    </button>
                    <button class="btn btn-square me-1" @click="onClone">
                        <Copy />
                    </button>
                    <button class="btn btn-square" @click="onDelete">
                        <Trash />
                    </button>
                </div>
                <input v-model="editName" type="text" class="input w-full" />
                <CronInput v-model="editCron" :edit-mode="editMode" />
            </div>
        </template>
    </div>
</template>
