<template>
    <MalioDrawer v-model="drawerOpen">
        <template #header>
            <h2 class="text-[32px] font-semibold text-primary-500">Récapitulatif Salaire</h2>
        </template>
        <form class="space-y-4" @submit.prevent="handleSubmit">
            <div>
                <label class="text-md font-semibold text-neutral-700" for="salary-recap-month">
                    Mois <span class="text-red-600">*</span>
                </label>
                <input
                    id="salary-recap-month"
                    v-model="selectedMonth"
                    type="month"
                    :class="monthFieldClass"
                />
                <p v-if="showMonthError" class="mt-1 text-sm text-red-600">
                    Le mois est obligatoire.
                </p>
            </div>

            <div class="flex justify-center pt-2">
                <MalioButton
                    label="Imprimer"
                    button-class="w-[200px]"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'

const props = defineProps<{
    modelValue: boolean
}>()

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

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

const now = new Date()
const defaultMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
const selectedMonth = ref(defaultMonth)
const validationTouched = ref(false)

const isMonthValid = computed(() => selectedMonth.value.trim() !== '')
const showMonthError = computed(() => validationTouched.value && !isMonthValid.value)

const baseInputClass = 'mt-2 w-full rounded-md border px-3 py-2 text-md text-neutral-900'
const monthFieldClass = computed(() => {
    if (showMonthError.value) {
        return `${baseInputClass} border-red-500`
    }
    return `${baseInputClass} border-neutral-300`
})

const handleSubmit = () => {
    validationTouched.value = true
    if (!isMonthValid.value) return
    emit('submit', selectedMonth.value)
}

watch(
    () => props.modelValue,
    (isOpen) => {
        if (!isOpen) {
            validationTouched.value = false
        }
    }
)
</script>
