<template>
    <AppDrawer v-model="drawerOpen" title="Nouvelle absence">
        <form class="space-y-4" @submit.prevent="handleSubmit">
            <MalioSelect
                :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
                :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" for="start-date">Début</label>
                    <div class="mt-2 grid grid-cols-2 gap-2">
                        <input
                            id="start-date"
                            v-model="absenceForm.startDate"
                            type="date"
                            :class="[dateInputBaseClass, absenceForm.startDate ? 'border-black' : 'border-m-muted']"
                            :disabled="props.lockDates"
                        />
                        <MalioSelect
                            :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" for="end-date">Fin</label>
                    <div class="mt-2 grid grid-cols-2 gap-2">
                        <input
                            id="end-date"
                            v-model="absenceForm.endDate"
                            type="date"
                            :class="[dateInputBaseClass, absenceForm.endDate ? 'border-black' : 'border-m-muted']"
                            :disabled="props.lockDates"
                        />
                        <MalioSelect
                            :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">
                <button
                    type="button"
                    class="flex items-center justify-center rounded-md bg-red-500 px-4 py-2 text-md font-semibold text-white hover:bg-red-600"
                    @click="handleDelete"
                >
                    Supprimer
                </button>
                <button
                    type="submit"
                    class="flex items-center justify-center rounded-md bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
                    :class="submitButtonClass"
                >
                    Modifier
                </button>
            </div>
            <div v-else class="flex justify-center pt-2">
                <MalioButton
                    type="submit"
                    label="Valider"
                    button-class="w-[200px]"
                    :disabled="props.isSubmitting || !isFormValid"
                />
            </div>
        </form>
    </AppDrawer>
</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'
import AppDrawer from '~/components/AppDrawer.vue'

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 submitButtonClass = computed(() => {
    if (props.isSubmitting || !isFormValid.value) {
        return 'opacity-50 cursor-not-allowed'
    }
    return ''
})

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 dateInputBaseClass =
    'h-10 w-full rounded-md border px-3 text-md text-black outline-none focus:border-2 focus:border-m-primary'

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>
