<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un projet' : 'Ajouter un projet'">
        <form @submit.prevent="handleSubmit" class="flex flex-col gap-2">
            <MalioInputText
                v-model="form.code"
                label="Code"
                input-class="w-full uppercase"
                :disabled="isEditing"
                :error="touched.code && !form.code.trim() ? 'Le code est requis' : touched.code && !/^[A-Z]{2,10}$/.test(form.code.trim()) ? '2 à 10 lettres majuscules' : ''"
                @blur="touched.code = true"
                @input="form.code = form.code.toUpperCase().replace(/[^A-Z]/g, '')"
            />
            <MalioInputText
                v-model="form.name"
                label="Titre"
                input-class="w-full"
                :error="touched.name && !form.name.trim() ? 'Le titre est requis' : ''"
                @blur="touched.name = true"
            />
            <MalioInputTextArea
                v-model="form.description"
                label="Description"
                :size="3"
            />
            <MalioSelect
                v-model="form.clientId"
                :options="clientOptions"
                label="Client"
                empty-option-label="Aucun client"
                min-width="w-full"
            />
            <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 { Project, ProjectWrite } from '~/services/dto/project'
import type { Client } from '~/services/dto/client'
import { useProjectService } from '~/services/projects'

const props = defineProps<{
    modelValue: boolean
    project: Project | null
    clients: Client[]
}>()

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

const form = reactive({
    code: '',
    name: '',
    description: '',
    color: '#222783',
    clientId: null as number | null,
})

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

const clientOptions = computed(() =>
    props.clients.map(c => ({ label: c.name, value: c.id }))
)

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.project) {
            form.code = props.project.code ?? ''
            form.name = props.project.name ?? ''
            form.description = props.project.description ?? ''
            form.color = props.project.color ?? '#222783'
            form.clientId = props.project.client?.id ?? null
        } else {
            form.code = ''
            form.name = ''
            form.description = ''
            form.color = '#222783'
            form.clientId = null
        }
        touched.code = false
        touched.name = false
    }
})

const { create, update } = useProjectService()

async function handleSubmit() {
    touched.name = true
    touched.code = true
    if (!form.name.trim()) return
    if (!isEditing.value && (!form.code.trim() || !/^[A-Z]{2,10}$/.test(form.code.trim()))) return

    isSubmitting.value = true
    try {
        const payload: ProjectWrite = {
            name: form.name.trim(),
            description: form.description.trim() || null,
            color: form.color,
            client: form.clientId ? `/api/clients/${form.clientId}` : null,
        }

        if (isEditing.value && props.project) {
            await update(props.project.id, payload)
        } else {
            payload.code = form.code.trim()
            await create(payload)
        }

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