<template>
    <MalioDrawer v-model="isOpen">
        <template #header>
            <h2 class="text-xl font-bold">{{ isEditing ? $t('prestataires.editPrestataire') : $t('prestataires.addPrestataire') }}</h2>
        </template>
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.name"
                :label="$t('prestataires.fields.name')"
                input-class="w-full"
                :error="touched.name && !form.name.trim() ? $t('directory.validation.nameRequired') : ''"
                @blur="touched.name = true"
            />

            <div class="mt-6 flex justify-end">
                <MalioButton
                    :label="$t('common.save')"
                    button-class="w-auto px-6"
                    :disabled="isSubmitting"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import type { Prestataire, PrestataireWrite } from '~/modules/directory/services/dto/prestataire'
import { usePrestataireService } from '~/modules/directory/services/prestataires'

const props = defineProps<{
    modelValue: boolean
    prestataire: Prestataire | null
}>()

const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'saved'): void
}>()

const isOpen = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

const isEditing = computed(() => !!props.prestataire)
const isSubmitting = ref(false)

const form = reactive({
    name: '',
})

const touched = reactive({
    name: false,
})

watch(() => props.modelValue, (open) => {
    if (open) {
        form.name = props.prestataire?.name ?? ''
        touched.name = false
    }
})

const { create, update } = usePrestataireService()

async function handleSubmit() {
    touched.name = true
    if (!form.name.trim()) return

    isSubmitting.value = true
    try {
        const payload: PrestataireWrite = {
            name: form.name.trim(),
        }

        if (isEditing.value && props.prestataire) {
            await update(props.prestataire.id, payload)
        } else {
            await create(payload)
        }

        emit('saved')
        isOpen.value = false
    } finally {
        isSubmitting.value = false
    }
}
</script>
