<template>
    <MalioDrawer v-model="isOpen">
        <template #header>
            <h2 class="text-xl font-bold">{{ isEditing ? $t('taskPriorities.editPriority') : $t('taskPriorities.addPriority') }}</h2>
        </template>
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.label"
                label="Libellé"
                input-class="w-full"
                :error="touched.label && !form.label.trim() ? 'Le libellé est requis' : ''"
                @blur="touched.label = true"
            />
            <div class="mt-4">
                <ColorPicker v-model="form.color" />
            </div>

            <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 { TaskPriority, TaskPriorityWrite } from '~/services/dto/task-priority'
import { useTaskPriorityService } from '~/services/task-priorities'

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

const form = reactive({
    label: '',
    color: '#222783',
})

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

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.item) {
            form.label = props.item.label ?? ''
            form.color = props.item.color ?? '#222783'
        } else {
            form.label = ''
            form.color = '#222783'
        }
        touched.label = false
    }
})

const { create, update } = useTaskPriorityService()

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

    isSubmitting.value = true
    try {
        const payload: TaskPriorityWrite = {
            label: form.label.trim(),
            color: form.color,
        }

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

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