<script setup lang="ts">
import { ref, onBeforeMount, watch, defineAsyncComponent } from "vue";
import { getCron, parseCron, validCron } from "@/lib/recurrence";
import { CronType } from "@/enums";
const DateInput = defineAsyncComponent(
    () => import("@/components/DateInput.vue"),
);

const DEFAULT_CRON = "0 0 * * *";

const cron = defineModel<string | null>({ required: true });
const rawCron = ref<string>(DEFAULT_CRON);
const valid = ref<boolean>(true);
const props = defineProps<{ editMode: boolean }>();

const cronType = ref<CronType>(CronType.MANUAL);
const cronValue = ref<string>("0");
const cronDate = ref<Date>(new Date());

function onCronChanged() {
    const data = parseCron(cron.value);
    rawCron.value = cron.value ?? DEFAULT_CRON;
    cronType.value = data.type;
    cronValue.value = data.value.toFixed(0);
    cronDate.value = data.date ?? new Date();
}

function updateCron() {
    cron.value = getCron(
        cronType.value,
        parseInt(cronValue.value),
        cronDate.value,
        rawCron.value,
    );
}

function onChangeCronType() {
    switch (cronType.value) {
        case CronType.EVERY_DAY:
            cronValue.value = "0";
            break;
        case CronType.EVERY_WEEK:
        case CronType.EVERY_MONTH:
        case CronType.EVERY_YEAR:
        case CronType.EVERY_N_DAYS:
        case CronType.EVERY_N_WEEKS:
        case CronType.EVERY_N_MONTHS:
            cronValue.value = "1";
            break;
        case CronType.CUSTOM:
            cron.value ??= DEFAULT_CRON;
            break;
    }
    updateCron();
}

function onChangeCronValue() {
    updateCron();
}

function onChangeCronDate() {
    updateCron();
}

function onInputRawCron() {
    valid.value = validCron(rawCron.value);
    if (valid.value) {
        updateCron();
    }
}

onBeforeMount(onCronChanged);

watch(cron, () => {
    if (!props.editMode) {
        onCronChanged();
    }
});
</script>

<template>
    <div class="flex gap-2 flex-wrap">
        <select
            v-model="cronType"
            class="select flex-1"
            @change="onChangeCronType"
        >
            <option :value="CronType.MANUAL">
                {{ $t("cron.type.manual") }}
            </option>
            <option :value="CronType.EVERY_DAY">
                {{ $t("cron.type.every_day") }}
            </option>
            <option :value="CronType.EVERY_N_DAYS">
                {{ $t("cron.type.every_n_days") }}
            </option>
            <option :value="CronType.EVERY_WEEK">
                {{ $t("cron.type.every_week") }}
            </option>
            <option :value="CronType.EVERY_N_WEEKS">
                {{ $t("cron.type.every_n_weeks") }}
            </option>
            <option :value="CronType.EVERY_MONTH">
                {{ $t("cron.type.every_month") }}
            </option>
            <option :value="CronType.EVERY_N_MONTHS">
                {{ $t("cron.type.every_n_months") }}
            </option>
            <option :value="CronType.EVERY_YEAR">
                {{ $t("cron.type.every_year") }}
            </option>
            <option :value="CronType.CUSTOM">
                {{ $t("cron.type.custom") }}
            </option>
            <option :value="CronType.ONE_TIME">
                {{ $t("cron.type.one_time") }}
            </option>
        </select>
        <select
            v-if="cronType === CronType.EVERY_DAY"
            v-model="cronValue"
            class="select flex-1"
            @change="onChangeCronValue"
        >
            <option
                v-for="i in Array.from(Array(24).keys())"
                :key="`h${i + 1}`"
                :value="i"
            >
                {{ i.toFixed(0).padStart(2, "0") }}:00
            </option>
        </select>
        <select
            v-if="cronType === CronType.EVERY_WEEK"
            v-model="cronValue"
            class="select flex-1"
            @change="onChangeCronValue"
        >
            <option
                v-for="i in Array.from(Array(7).keys())"
                :key="`w${i + 1}`"
                :value="i + 1"
            >
                {{ $t(`cron.week.${i.toFixed(0)}`) }}
            </option>
        </select>
        <select
            v-if="cronType === CronType.EVERY_MONTH"
            v-model="cronValue"
            class="select flex-1"
            @change="onChangeCronValue"
        >
            <option :value="1">{{ $t("cron.month.first_day") }}</option>
            <option :value="32">{{ $t("cron.month.last_day") }}</option>
            <option
                v-for="i in Array.from(Array(7).keys())"
                :key="`d${-(i + 1)}`"
                :value="-(i + 1)"
            >
                {{ $t("cron.month.first") }}
                {{ $t(`cron.week.${i.toFixed(0)}`).toLowerCase() }}
            </option>
            <option
                v-for="i in Array.from(Array(7).keys())"
                :key="`d${-(i + 8)}`"
                :value="-(i + 8)"
            >
                {{ $t("cron.month.last") }}
                {{ $t(`cron.week.${i.toFixed(0)}`).toLowerCase() }}
            </option>
            <option
                v-for="i in Array.from(Array(30).keys())"
                :key="`d${i + 2}`"
                :value="i + 2"
            >
                {{
                    i % 10 == 9 && i !== 9
                        ? $t("cron.month.st", [i + 2])
                        : i % 10 === 0 && i !== 10
                          ? $t("cron.month.nd", [i + 2])
                          : i % 10 === 1 && i !== 11
                            ? $t("cron.month.rd", [i + 2])
                            : $t("cron.month.th", [i + 2])
                }}
            </option>
        </select>
        <select
            v-if="cronType === CronType.EVERY_YEAR"
            v-model="cronValue"
            class="select flex-1"
            @change="onChangeCronValue"
        >
            <option
                v-for="i in Array.from(Array(12).keys())"
                :key="`m${i}`"
                :value="i + 1"
            >
                {{ $t(`cron.year.${i.toFixed(0)}`) }}
            </option>
        </select>
        <input
            v-if="cronType === CronType.CUSTOM"
            v-model="rawCron"
            type="text"
            class="input font-mono flex-1"
            :class="valid ? '' : 'input-error'"
            @input="onInputRawCron"
        />
        <input
            v-if="
                cronType === CronType.EVERY_N_DAYS ||
                cronType === CronType.EVERY_N_WEEKS ||
                cronType === CronType.EVERY_N_MONTHS
            "
            v-model="cronValue"
            type="number"
            min="1"
            step="1"
            class="input font-mono flex-1"
            @change="onChangeCronValue"
        />
        <label
            v-if="
                cronType === CronType.EVERY_N_DAYS ||
                cronType === CronType.EVERY_N_WEEKS ||
                cronType === CronType.EVERY_N_MONTHS
            "
            class="label flex-1 basis-full"
        >
            {{ $t("cron.rrule_start") }}
            <date-input
                v-model="cronDate"
                required
                class="input font-mono"
                @change="onChangeCronDate"
            />
        </label>
    </div>
</template>
