<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un groupe' : 'Ajouter un groupe'">
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.title"
                label="Titre"
                input-class="w-full"
                :error="touched.title && !form.title.trim() ? 'Le titre est requis' : ''"
                @blur="touched.title = true"
            />
            <MalioInputTextArea
                v-model="form.description"
                label="Description"
                :size="3"
            />
            <div class="mt-4">
                <ColorPicker v-model="form.color" />
            </div>

            <div class="mt-6 flex justify-end">
                <button
                    type="submit"
                    class="rounded-md bg-primary-500 px-6 py-2 text-sm font-semibold text-white hover:bg-secondary-500 disabled:cursor-not-allowed disabled:opacity-50"
                    :disabled="isSubmitting"
                >
                    Enregistrer
                </button>
            </div>
        </form>
    </AppDrawer>
</template>

<script setup lang="ts">
import type { TaskGroup, TaskGroupWrite } from '~/services/dto/task-group'
import { useTaskGroupService } from '~/services/task-groups'

const props = defineProps<{
    modelValue: boolean
    group: TaskGroup | null
    projectId: number
}>()

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.group)
const isSubmitting = ref(false)

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

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

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

const { create, update } = useTaskGroupService()

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

    isSubmitting.value = true
    try {
        const payload: TaskGroupWrite = {
            title: form.title.trim(),
            description: form.description.trim() || null,
            color: form.color,
            project: `/api/projects/${props.projectId}`,
        }

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

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