<template>
    <MalioDrawer v-model="isOpen">
        <template #header>
            <h2 class="text-xl font-bold">{{ isEditing ? $t('clients.editClient') : $t('clients.addClient') }}</h2>
        </template>
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.name"
                label="Nom société"
                input-class="w-full"
                :error="touched.name && !form.name.trim() ? 'Le nom est requis' : ''"
                @blur="touched.name = true"
            />

            <div class="mt-6 flex justify-end">
                <MalioButton
                    label="Enregistrer"
                    button-class="w-auto px-6"
                    :disabled="isSubmitting"
                    @click="handleSubmit"
                />
            </div>
        </form>
    </MalioDrawer>
</template>

<script setup lang="ts">
import type { Client, ClientWrite } from '~/modules/directory/services/dto/client'
import { useClientService } from '~/modules/directory/services/clients'

const props = defineProps<{
    modelValue: boolean
    client: Client | 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.client)
const isSubmitting = ref(false)

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

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

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

const { create, update } = useClientService()

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

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

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

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