<script
    setup
    lang="ts"
>
    import { useI18n } from 'vue-i18n';
    import { computed, ref, watch } from 'vue';
    import { deepEqual } from 'src/utils/deep-equal';
    import { useUiStore } from 'src/stores/ui-store';
    import { useExpensesStore } from 'src/stores/expense-store';
    import { useTimesheetStore } from 'src/stores/timesheet-store';
    import { useExpensesApi } from 'src/modules/timesheets/composables/use-expense-api';
    import { convertToMonetaryAmount, getExpenseIcon, useExpenseRules } from 'src/modules/timesheets/utils/expense.util';
    import { type ExpenseType, TYPES_WITH_AMOUNT_ONLY } from 'src/modules/timesheets/models/expense.models';

    interface ExpenseOption {
        label: string;
        value: ExpenseType;
        icon: string;
    }

    const { t } = useI18n();
    const ui_store = useUiStore();
    const timesheet_store = useTimesheetStore();
    const expenses_store = useExpensesStore();
    const expenses_api = useExpensesApi();
    const files = defineModel<File[] | null>('files');

    const is_navigator_open = ref(false);
    const is_initial_expense = ref(true);

    const COMMENT_MAX_LENGTH = 280;
    const rules = useExpenseRules(t);

    const period_start_date = computed(() => timesheet_store.pay_period?.period_start.replaceAll('-', '/') ?? '');
    const period_end_date = computed(() => timesheet_store.pay_period?.period_end.replaceAll('-', '/') ?? '');

    const expense_options: ExpenseOption[] = [
        {label: t('timesheet.expense.types.PER_DIEM'), value: 'PER_DIEM', icon: getExpenseIcon('PER_DIEM')},
        {label: t('timesheet.expense.types.EXPENSES'), value: 'EXPENSES', icon: getExpenseIcon('EXPENSES')},
        {label: t('timesheet.expense.types.MILEAGE'), value: 'MILEAGE', icon: getExpenseIcon('MILEAGE')},
        {label: t('timesheet.expense.types.ON_CALL'), value: 'ON_CALL', icon: getExpenseIcon('ON_CALL')},
    ]
    const expense_selected = ref(expense_options.find(expense => expense.value == expenses_store.current_expense.type));

    const emit = defineEmits<{
        'onClickUpdateCancel': [void];
        'onClickSaveUpdates': [void];
    }>();

    const openDatePicker = () => {
        is_navigator_open.value = true;
        if (expenses_store.current_expense.date === undefined) {
            expenses_store.current_expense.date = timesheet_store.pay_period?.period_start ?? '';
        }
    };

    const closeDatePicker = (date: string) => {
        is_navigator_open.value = false;
        expenses_store.current_expense.date = date;
    }

    const requestExpenseCreationOrUpdate = async () => {
        await expenses_api.upsertExpense(expenses_store.current_expense);
        
        if (expenses_store.current_expense.id) {
            emit('onClickSaveUpdates');
        }

    };

    watch(expenses_store.current_expense, () => {
        is_initial_expense.value = deepEqual(expenses_store.current_expense, expenses_store.initial_expense);
    });
</script>

<template>
    <q-form
        v-if="!timesheet_store.timesheets?.every(timesheet => timesheet.is_approved)"
        :key="expenses_store.current_expense.id"
        flat
        @submit.prevent="requestExpenseCreationOrUpdate"
        class="full-width"
    >
        <div
            class="text-uppercase text-weight-medium q-pt-sm q-ma-sm"
            :class="expenses_store.mode === 'create' ? 'q-px-lg' : 'invisible'"
        >
            {{ $t('timesheet.expense.add_expense') }}
        </div>
        <div
            class="row justify-between items-start rounded-5 q-pb-sm"
            :class="expenses_store.mode === 'create' ? 'q-px-lg' : ''"
        >
            <!-- date selection input -->
            <q-input
                v-model="expenses_store.current_expense.date"
                dense
                type="date"
                borderless
                readonly
                stack-label
                color="primary"
                class="col-auto q-px-xs"
                input-class="text-weight-medium"
                input-style="font-size: 1em;"
                :label="$t('timesheet.expense.date')"
            >
                <template #prepend>
                    <q-btn
                        push
                        dense
                        icon="event"
                        color="accent"
                        class="q-mr-sm"
                        @click="openDatePicker"
                    />

                    <q-dialog
                        v-model="is_navigator_open"
                        transition-show="jump-right"
                        transition-hide="jump-right"
                    >
                        <q-date
                            v-model="expenses_store.current_expense.date"
                            mask="YYYY-MM-DD"
                            event-color="accent"
                            :options="date => date >= period_start_date && date <= period_end_date"
                            @update:model-value="closeDatePicker"
                        />
                    </q-dialog>
                </template>

                <template #label>
                    <span class="text-weight-bold text-accent text-uppercase text-caption">
                        {{ $t('timesheet.expense.date') }}
                    </span>
                </template>
            </q-input>

            <!-- expenses type selection -->
            <q-select
                v-model="expense_selected"
                standout="bg-blue-grey-9"
                dense
                :options="expense_options"
                hide-dropdown-icon
                stack-label
                label-slot
                class="col q-px-xs"
                color="primary"
                :label="$t('timesheet.expense.type')"
                :menu-offset="[0, 10]"
                menu-anchor="bottom middle"
                menu-self="top middle"
                popup-content-class="text-uppercase text-weight-bold text-center rounded-5"
                popup-content-style="border: 2px solid var(--q-accent)"
                :rules="[rules.typeRequired]"
                @update:model-value="option => expenses_store.current_expense.type = option.value"
            >
                <template #label>
                    <span class="text-weight-bold text-accent text-uppercase text-caption">
                        {{ $t('timesheet.expense.type') }}
                    </span>
                </template>

                <template #selected-item="scope">
                    <div
                        class="row items-center text-weight-bold q-ma-none q-pa-none no-wrap ellipsis full-width"
                        :class="ui_store.is_mobile_mode ? 'full-height' : ''"
                        :tabindex="scope.tabindex"
                    >
                        <q-icon
                            :name="scope.opt.icon"
                            size="xs"
                            class="col-auto q-mx-xs"
                        />
                        <span
                            style="line-height: 1em;"
                            class="col-auto ellipsis text-uppercase"
                        >{{ scope.opt.label }}</span>
                    </div>
                </template>
            </q-select>

            <!-- amount input -->
            <div v-if="TYPES_WITH_AMOUNT_ONLY.includes(expenses_store.current_expense?.type ?? 'EXPENSES')">
                <q-input
                    key="amount"
                    v-model.number="expenses_store.current_expense.amount"
                    standout="bg-blue-grey-9"
                    dense
                    label-slot
                    stack-label
                    suffix="$"
                    color="primary"
                    class="col-auto q-px-xs"
                    input-class="text-right text-weight-bold"
                    :input-style="'font-size: 1.2em;'"
                    lazy-rules="ondemand"
                    :rules="[rules.amountRequired]"
                    @blur="expenses_store.current_expense.amount = convertToMonetaryAmount(expenses_store.current_expense.amount)"
                >
                    <template #label>
                        <span class="text-weight-bold text-accent text-uppercase text-caption">
                            {{ $t('timesheet.expense.amount') }}
                        </span>
                    </template>
                </q-input>
            </div>

            <!-- mileage input -->
            <div v-else>
                <q-input
                    key="mileage"
                    v-model.number="expenses_store.current_expense.mileage"
                    standout="bg-blue-grey-9"
                    input-class="text-right"
                    dense
                    stack-label
                    clearable
                    color="primary"
                    class="col q-px-xs"
                    label-slot
                    suffix="km"
                    lazy-rules="ondemand"
                    :rules="[rules.mileageRequired]"
                >
                    <template #label>
                        <span class="text-weight-bold text-accent text-uppercase text-caption">
                            {{ $t('timesheet.expense.mileage') }}
                        </span>
                    </template>
                </q-input>
            </div>

            <!-- employee comment input -->
            <q-input
                v-model="expenses_store.current_expense.comment"
                standout="bg-blue-grey-9"
                dense
                stack-label
                label-slot
                color="primary"
                type="text"
                class="col q-px-sm"
                :maxlength="COMMENT_MAX_LENGTH"
                lazy-rules="ondemand"
                :rules="[rules.commentRequired]"
            >
                <template #label>
                    <span class="text-weight-bold text-accent text-uppercase text-caption">
                        {{ $t('timesheet.expense.employee_comment') }}
                    </span>
                </template>
            </q-input>

            <!-- import attach file section -->
            <q-file
                v-model="files"
                standout="bg-blue-grey-9"
                dense
                use-chips
                multiple
                stack-label
                :label="$t('timesheet.expense.hints.attach_file')"
                class="col"
                style="max-width: 300px;"
            >
                <template #prepend>
                    <q-icon
                        name="attach_file"
                        size="sm"
                        color="accent"
                    />
                </template>

                <template #label>
                    <span class="text-weight-bold text-accent text-uppercase text-caption">
                        {{ $t('timesheet.expense.hints.attach_file') }}
                    </span>
                </template>
            </q-file>
        </div>
        <div class="col row full-width items-center">
            <q-space />

            <q-btn
                v-if="expenses_store.mode === 'update'"
                flat
                dense
                class="col-auto q-ml-sm"
                icon="clear"
                color="negative"
                :label="$q.screen.gt.sm ? $t('shared.label.cancel') : ''"
                @click="$emit('onClickUpdateCancel')"
            />

            <q-btn
                push
                :disable="is_initial_expense"
                :color="is_initial_expense ? 'grey-5' : 'accent'"
                :icon="expenses_store.mode === 'update' ? 'save' : 'upload'"
                :label="expenses_store.mode === 'update' ? $t('shared.label.update') : $t('shared.label.add')"
                class="q-px-sm "
                :class="expenses_store.mode === 'create' ? 'q-mr-lg q-mb-md' : 'q-mb-sm q-ml-lg'"
                type="submit"
            />
        </div>
    </q-form>
</template>