<template>
    <AppDrawer v-model="drawerOpen" title="Récapitulatif Salaire">
        <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">
                <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"
                >
                    Imprimer
                </button>
            </div>
        </form>
    </AppDrawer>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import AppDrawer from '~/components/AppDrawer.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 submitButtonClass = computed(() => {
    if (!isMonthValid.value) {
        return 'opacity-50 cursor-not-allowed'
    }
    return ''
})

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

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