<script setup>
import WorkerEventLabel from 'pages/Worker/Card/WorkerEventLabel.vue';
import FetchData from 'components/FetchData.vue';
import { useI18n } from 'vue-i18n';
import VnSelect from 'components/common/VnSelect.vue';
import useNotify from 'src/composables/useNotify';
import { useRoute } from 'vue-router';
import { computed, ref, watch } from 'vue';
import { toDateFormat } from '../../../filters/date';
const { notify } = useNotify();

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

const props = defineProps({
    businessFk: {
        type: Number,
        default: null,
    },
    year: {
        type: [Number, String],
        default: null,
    },
    absenceType: {
        type: Object,
        default: null,
    },
    contractHolidays: {
        type: Object,
        default: null,
    },
    yearHolidays: {
        type: Object,
        default: null,
    },
});

watch(
    () => props.contractHolidays,
    (newValue) => {
        checkHolidays(newValue);
    },
    { deep: true, immediate: true }
);
const emit = defineEmits(['update:businessFk', 'update:year', 'update:absenceType']);

const selectedBusinessFk = computed({
    get: () => props.businessFk,
    set: (value) => emit('update:businessFk', value),
});

const selectedYear = computed({
    get: () => props.year,
    set: (value) => emit('update:year', value),
});

const selectedAbsenceType = computed({
    get: () => props.absenceType,
    set: (value) => {
        if (value === props.absenceType) value = null;
        emit('update:absenceType', value);
    },
});

function generateYears() {
    const now = Date.vnNew();
    const maxYear = now.getFullYear() + 1;

    return Array.from({ length: 5 }, (_, i) => String(maxYear - i)) || [];
}

function checkHolidays(contractHolidays) {
    if (!contractHolidays) return;
    if (
        contractHolidays.holidaysEnjoyed > contractHolidays.totalHolidays ||
        contractHolidays.hoursEnjoyed > contractHolidays.totalHours
    ) {
        notify(t('Vacation days have been exceeded'), 'negative');
    }
}

const absenceTypeList = ref([]);
const contractList = ref([]);
const yearList = ref(generateYears());
</script>

<template>
    <FetchData
        url="AbsenceTypes"
        @on-fetch="(data) => (absenceTypeList = data)"
        auto-load
    />
    <FetchData
        :url="`Workers/${route.params.id}/contracts`"
        :filter="{ fields: ['businessFk', 'started', 'ended'] }"
        @on-fetch="(data) => (contractList = data)"
        auto-load
    />

    <div
        v-if="contractHolidays"
        class="q-pa-md q-mb-md q-ma-md color-vn-text"
        style="border: 2px solid black"
    >
        <QCardSection horizontal>
            <span class="text-weight-bold text-subtitle1 text-center full-width">
                {{ t('Contract') }} #{{ selectedBusinessFk }}
            </span>
        </QCardSection>
        <QCardSection class="column items-center" horizontal>
            <span>
                {{
                    t('usedDays', {
                        holidaysEnjoyed: contractHolidays.holidaysEnjoyed || 0,
                        totalHolidays: contractHolidays.totalHolidays || 0,
                    })
                }}
            </span>
        </QCardSection>
        <QCardSection class="column items-center" horizontal>
            <span>
                {{
                    t('spentHours', {
                        hoursEnjoyed: contractHolidays.hoursEnjoyed || 0,
                        totalHours: contractHolidays.totalHours || 0,
                    })
                }}
            </span>
        </QCardSection>
        <QCardSection class="column items-center" horizontal>
            <span>
                {{
                    t('paidHolidays', {
                        payedHolidays: contractHolidays.payedHolidays || 0,
                    })
                }}
            </span>
        </QCardSection>
    </div>
    <div
        v-if="yearHolidays"
        class="q-pa-md q-mb-md q-ma-md color-vn-text"
        style="border: 2px solid black"
    >
        <QCardSection horizontal>
            <span class="text-weight-bold text-subtitle1 text-center full-width">
                {{ t('Year') }} {{ selectedYear }}
            </span>
        </QCardSection>
        <QCardSection class="column items-center" horizontal>
            <span>
                {{
                    t('usedDays', {
                        holidaysEnjoyed: yearHolidays.holidaysEnjoyed || 0,
                        totalHolidays: yearHolidays.totalHolidays || 0,
                    })
                }}
            </span>
        </QCardSection>
        <QCardSection class="column items-center" horizontal>
            {{
                t('spentHours', {
                    hoursEnjoyed: yearHolidays.hoursEnjoyed || 0,
                    totalHours: yearHolidays.totalHours || 0,
                })
            }}
        </QCardSection>
    </div>
    <QList dense class="list q-gutter-y-sm q-my-lg">
        <QItem>
            <QItemSection>
                <VnSelect
                    :label="t('Year')"
                    v-model="selectedYear"
                    :options="yearList"
                    dense
                    outlined
                    rounded
                    use-input
                    :is-clearable="false"
                />
            </QItemSection>
        </QItem>
        <QItem>
            <QItemSection>
                <VnSelect
                    :label="t('Contract')"
                    v-model="selectedBusinessFk"
                    :options="contractList"
                    option-value="businessFk"
                    option-label="businessFk"
                    dense
                    outlined
                    rounded
                    use-input
                    :is-clearable="false"
                >
                    <template #option="scope">
                        <QItem v-bind="scope.itemProps">
                            <QItemSection>
                                <QItemLabel># {{ scope.opt?.businessFk }}</QItemLabel>
                                <QItemLabel caption>
                                    {{ toDateFormat(scope.opt?.started) }} -
                                    {{
                                        scope.opt?.ended
                                            ? toDateFormat(scope.opt?.ended)
                                            : 'Indef.'
                                    }}
                                </QItemLabel>
                            </QItemSection>
                        </QItem>
                    </template>
                </VnSelect>
            </QItemSection>
        </QItem>
    </QList>
    <QList dense class="list q-gutter-y-xs q-my-md">
        <QItem v-for="type in absenceTypeList" :key="type.id">
            <WorkerEventLabel
                :color="type.rgb"
                :selected="selectedAbsenceType?.id === type.id"
                @click="selectedAbsenceType = type"
            >
                {{ type.name }}
            </WorkerEventLabel>
        </QItem>
    </QList>
    <QSeparator />
    <QList dense class="list q-my-md no-pointer-events">
        <QItem>
            <WorkerEventLabel avatar-class="worker-calendar-festive">
                {{ t('Festive') }}
            </WorkerEventLabel>
            <WorkerEventLabel avatar-class="worker-calendar-today">
                {{ t('Current day') }}
            </WorkerEventLabel>
        </QItem>
    </QList>
</template>

<style lang="scss">
.worker-calendar-festive {
    border: 2px solid $negative;
}

.worker-calendar-today {
    border: 2px solid $info;
}
</style>

<i18n>
en:
    spentHours: Spent {hoursEnjoyed} of {totalHours} hours
    usedDays: Used {holidaysEnjoyed} of {totalHolidays} days
    paidHolidays: Paid holidays {payedHolidays} days

es:
    Paid holidays: Vacaciones pagadas
    Year: Año
    Contract: Contrato
    Festive: Festivo
    Current day: Día actual
    spentHours: Utilizadas {hoursEnjoyed} de {totalHours} horas
    usedDays: Utilizados {holidaysEnjoyed} de {totalHolidays} días
    paidHolidays: Vacaciones pagadas {payedHolidays} días

</i18n>
