<template>
    <AppDrawer v-model="drawerOpen" title="Nouvelle absence">
        <form class="space-y-4" @submit.prevent="handleSubmit">
            <div>
                <label class="text-md font-semibold text-neutral-700" for="employee">
                    Employé <span class="text-red-600">*</span>
                </label>
                <select
                    id="employee"
                    v-model="absenceForm.employeeId"
                    :class="employeeFieldClass"
                    :disabled="props.lockEmployee"
                >
                    <option value="" disabled>Choisir un employé</option>
                    <option v-for="employee in employees" :key="employee.id" :value="employee.id">
                        {{ employee.firstName }} {{ employee.lastName }}
                    </option>
                </select>
                <p v-if="showEmployeeError" class="mt-1 text-sm text-red-600">
                    L'employé est obligatoire.
                </p>
            </div>

            <div>
                <label class="text-md font-semibold text-neutral-700" for="type">
                    Type d'absence <span class="text-red-600">*</span>
                </label>
                <select
                    id="type"
                    v-model="absenceForm.typeId"
                    :class="typeFieldClass"
                >
                    <option value="" disabled>Choisir un type</option>
                    <option v-for="type in absenceTypes" :key="type.id" :value="type.id">
                        {{ type.label }} ({{ type.code }})
                    </option>
                </select>
                <p v-if="showTypeError" class="mt-1 text-sm text-red-600">
                    Le type d'absence est obligatoire.
                </p>
            </div>

            <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="w-full rounded-md border border-neutral-300 px-3 py-2 text-md text-neutral-900"
                            :disabled="props.lockDates"
                        />
                        <select
                            v-model="absenceForm.startHalf"
                            class="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-md text-neutral-900"
                        >
                            <option v-for="half in HALF_DAYS" :key="half.value" :value="half.value">
                                {{ half.label }}
                            </option>
                        </select>
                    </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="w-full rounded-md border border-neutral-300 px-3 py-2 text-md text-neutral-900"
                            :disabled="props.lockDates"
                        />
                        <select
                            v-model="absenceForm.endHalf"
                            class="w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-md text-neutral-900"
                        >
                            <option v-for="half in HALF_DAYS" :key="half.value" :value="half.value">
                                {{ half.label }}
                            </option>
                        </select>
                    </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">
                <button
                    type="submit"
                    class="flex w-[200px] items-center justify-center gap-2 rounded-md bg-primary-500 px-4 py-2 text-md font-semibold text-white hover:bg-secondary-500"
                    :class="submitButtonClass"
                >
                    + Ajouter
                </button>
            </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 baseSelectClass =
    'mt-2 w-full rounded-md border bg-white px-3 py-2 text-md text-neutral-900'
const employeeFieldClass = computed(() => {
    if (showEmployeeError.value) {
        return `${baseSelectClass} border-red-500`
    }
    return `${baseSelectClass} border-neutral-300`
})
const typeFieldClass = computed(() => {
    if (showTypeError.value) {
        return `${baseSelectClass} border-red-500`
    }
    return `${baseSelectClass} border-neutral-300`
})

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>
