<script setup>
import { reactive, ref, computed, onBeforeMount } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import VnSelect from 'src/components/common/VnSelect.vue';
import FormModelPopup from 'components/FormModelPopup.vue';
import VnInputTime from 'src/components/common/VnInputTime.vue';

const $props = defineProps({
    entryId: {
        type: Number,
        default: null,
    },
    entryCode: {
        type: String,
        default: null,
    },
    dated: {
        type: Date,
        default: true,
    },
});

const emit = defineEmits(['onDataSaved']);

const route = useRoute();
const { t } = useI18n();

let workerHourEntry = reactive({});

const entryDirections = [
    { code: 'in', description: t('Entrada') },
    { code: 'middle', description: t('Intermedio') },
    { code: 'out', description: t('Salida') },
];

const closeButton = ref(null);

const onDataSaved = (dataSaved) => {
    emit('onDataSaved', dataSaved);
    closeForm();
};

const closeForm = () => {
    if (closeButton.value) closeButton.value.click();
};

const isEditMode = computed(() => !!$props.entryId);

const title = computed(() => (isEditMode.value ? t('Edit entry') : t('Add time')));

const urlCreate = computed(() =>
    isEditMode.value
        ? `WorkerTimeControls/${$props.entryId}/updateTimeEntry`
        : `WorkerTimeControls/${route.params.id}/addTimeEntry`
);

onBeforeMount(() => {
    workerHourEntry = isEditMode.value
        ? { direction: $props.entryCode }
        : {
              timed: new Date($props.dated),
              workerFk: route.params.id,
          };
});
</script>

<template>
    <FormModelPopup
        :form-initial-data="workerHourEntry"
        :observe-form-changes="false"
        :default-actions="false"
        :title="title"
        :url-create="urlCreate"
        @on-data-saved="onDataSaved"
    >
        <template #form-inputs="{ data }">
            <VnInputTime
                v-if="!isEditMode"
                :label="t('Hour')"
                v-model="data.timed"
                autofocus
                :required="true"
                :is-clearable="false"
            />
            <VnSelect
                :label="t('Type')"
                v-model="data.direction"
                :options="entryDirections"
                option-value="code"
                option-label="description"
                hide-selected
            />
        </template>
    </FormModelPopup>
</template>

<i18n>
es:
    Add time: Añadir hora
    Edit entry: Editar entrada
    Hour: Hora
    Type: Tipo
    Entrada: Entrada
    Intermedio: Intermedio
    Salida: Salida
</i18n>
