<template>
    <MalioDrawer v-model="drawerOpen">
        <template #header>
            <h2 class="text-[32px] font-semibold text-primary-500">Nouvelle absence</h2>
        </template>
        <form class="space-y-4" @submit.prevent="handleSubmit">
            <MalioSelect :reserve-message-space="false"
                :model-value="absenceForm.employeeId === '' ? null : absenceForm.employeeId"
                :options="employeeOptions"
                label="Employé *"
                empty-option-label="Choisir un employé"
                min-width=""
                :disabled="props.lockEmployee"
                :error="showEmployeeError ? `L'employé est obligatoire.` : ''"
                @update:model-value="onEmployeeChange"
            />

            <MalioSelect :reserve-message-space="false"
                :model-value="absenceForm.typeId === '' ? null : absenceForm.typeId"
                :options="typeOptions"
                label="Type d'absence *"
                empty-option-label="Choisir un type"
                min-width=""
                :error="showTypeError ? `Le type d'absence est obligatoire.` : ''"
                @update:model-value="onTypeChange"
            />

            <div class="space-y-4">
                <div>
                    <label class="text-md font-semibold text-neutral-700">Début</label>
                    <div class="mt-2 space-y-2">
                        <MalioDate
                            v-model="absenceForm.startDate"
                            :clearable="false"
                            :reserve-message-space="false"
                            :disabled="props.lockDates"
                            group-class="w-full"
                        />
                        <MalioSelect :reserve-message-space="false"
                            :model-value="absenceForm.startHalf"
                            :options="halfDayOptions"
                            min-width=""
                            @update:model-value="(v) => { if (v !== null) absenceForm.startHalf = v as HalfDay }"
                        />
                    </div>
                </div>
                <div>
                    <label class="text-md font-semibold text-neutral-700">Fin</label>
                    <div class="mt-2 space-y-2">
                        <MalioDate
                            v-model="absenceForm.endDate"
                            :clearable="false"
                            :reserve-message-space="false"
                            :disabled="props.lockDates"
                            group-class="w-full"
                        />
                        <MalioSelect :reserve-message-space="false"
                            :model-value="absenceForm.endHalf"
                            :options="halfDayOptions"
                            min-width=""
                            @update:model-value="(v) => { if (v !== null) absenceForm.endHalf = v as HalfDay }"
                        />
                    </div>
                </div>
            </div>

            <div v-if="props.showComment !== false">
                <label class="text-md font-semibold text-neutral-700" for="comment">Commentaire</label>
                <textarea
                    id="comment"
                    v-model="absenceForm.comment"
                    rows="3"
                    class="mt-2 w-full rounded-md border border-neutral-300 px-3 py-2 text-md text-neutral-900"
                />
            </div>

            <div v-if="editingAbsence" class="grid grid-cols-2 gap-3 pt-2">
                <MalioButton
                    label="Supprimer"
                    variant="danger"
                    button-class="w-full"
                    @click="handleDelete"
                />
                <MalioButton
                    label="Modifier"
                    variant="primary"
                    button-class="w-full"
                    :disabled="props.isSubmitting || !isFormValid"
                    @click="handleSubmit"
                />
            </div>
            <div v-else class="flex justify-center pt-2">
                <MalioButton
                    label="Valider"
                    button-class="w-[200px]"
                    :disabled="props.isSubmitting || !isFormValid"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import { computed, reactive, toRef, watch } from 'vue'
import type { Employee } from '~/services/dto/employee'
import type { AbsenceType } from '~/services/dto/absence-type'
import type { Absence } from '~/services/dto/absence'
import type { HalfDay } from '~/services/dto/half-day'
import { HALF_DAYS } from '~/services/dto/half-day'

const props = defineProps<{
    modelValue: boolean
    employees: Employee[]
    absenceTypes: AbsenceType[]
    form: {
        employeeId: number | ''
        typeId: number | ''
        startDate: string
        startHalf: HalfDay
        endDate: string
        endHalf: HalfDay
        comment: string
    }
    editingAbsence: Absence | null
    isSubmitting: boolean
    lockEmployee?: boolean
    lockDates?: boolean
    showComment?: boolean
}>()

const emit = defineEmits<{
    (event: 'update:modelValue', value: boolean): void
    (event: 'submit'): void
    (event: 'delete'): void
    (event: 'cancel'): void
}>()

const drawerOpen = computed({
    get: () => props.modelValue,
    set: (value: boolean) => emit('update:modelValue', value)
})

const absenceForm = toRef(props, 'form')
const editingAbsence = toRef(props, 'editingAbsence')

const validationTouched = reactive({
    employee: false,
    type: false
})

const isEmployeeValid = computed(() => absenceForm.value.employeeId !== '')
const isTypeValid = computed(() => absenceForm.value.typeId !== '')
const isFormValid = computed(() => isEmployeeValid.value && isTypeValid.value)

const showEmployeeError = computed(
    () => validationTouched.employee && !isEmployeeValid.value
)
const showTypeError = computed(
    () => validationTouched.type && !isTypeValid.value
)

const employeeOptions = computed(() =>
    props.employees.map((e) => ({ label: `${e.firstName} ${e.lastName}`, value: e.id }))
)
const typeOptions = computed(() =>
    props.absenceTypes.map((t) => ({ label: `${t.label} (${t.code})`, value: t.id }))
)
const halfDayOptions = HALF_DAYS.map((h) => ({ label: h.label, value: h.value }))

const onEmployeeChange = (value: string | number | null) => {
    absenceForm.value.employeeId = value === null ? '' : Number(value)
}
const onTypeChange = (value: string | number | null) => {
    absenceForm.value.typeId = value === null ? '' : Number(value)
}

watch(
    () => props.modelValue,
    (isOpen) => {
        if (!isOpen) {
            validationTouched.employee = false
            validationTouched.type = false
        }
    }
)

const handleSubmit = () => {
    validationTouched.employee = true
    validationTouched.type = true
    if (!isEmployeeValid.value || !isTypeValid.value) return
    emit('submit')
}

const handleDelete = () => {
    emit('delete')
}

const handleCancel = () => {
    emit('cancel')
    emit('update:modelValue', false)
}
</script>
