<template>
    <AppDrawer v-model="isOpen" :title="isEditing ? 'Modifier un utilisateur' : 'Ajouter un utilisateur'">
        <form class="flex flex-col gap-2" @submit.prevent="handleSubmit">
            <MalioInputText
                v-model="form.username"
                label="Nom d'utilisateur"
                input-class="w-full"
                :error="touched.username && !form.username.trim() ? 'Le nom est requis' : ''"
                @blur="touched.username = true"
            />
            <MalioInputText
                v-model="form.password"
                label="Mot de passe"
                input-class="w-full"
                type="password"
                :placeholder="isEditing ? 'Laisser vide pour ne pas changer' : ''"
                :error="touched.password && !isEditing && !form.password ? 'Le mot de passe est requis' : ''"
                @blur="touched.password = true"
            />
            <div class="mt-4">
                <label class="text-sm font-semibold text-neutral-700">Rôles</label>
                <div class="mt-2 flex flex-col gap-2">
                    <label
                        v-for="role in availableRoles"
                        :key="role"
                        class="flex items-center gap-2 text-sm text-neutral-700"
                    >
                        <input
                            v-model="form.roles"
                            type="checkbox"
                            :value="role"
                            class="rounded border-neutral-300"
                        />
                        {{ role }}
                    </label>
                </div>
            </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 { UserData, UserWrite } from '~/services/dto/user-data'
import { useUserService } from '~/services/users'

const props = defineProps<{
    modelValue: boolean
    item: UserData | 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 availableRoles = ['ROLE_ADMIN', 'ROLE_USER']

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

const form = reactive({
    username: '',
    password: '',
    roles: [] as string[],
})

const touched = reactive({
    username: false,
    password: false,
})

watch(() => props.modelValue, (open) => {
    if (open) {
        if (props.item) {
            form.username = props.item.username ?? ''
            form.password = ''
            form.roles = [...props.item.roles]
        } else {
            form.username = ''
            form.password = ''
            form.roles = ['ROLE_USER']
        }
        touched.username = false
        touched.password = false
    }
})

const { create, update } = useUserService()

async function handleSubmit() {
    touched.username = true
    touched.password = true
    if (!form.username.trim()) return
    if (!isEditing.value && !form.password) return

    isSubmitting.value = true
    try {
        const payload: UserWrite = {
            username: form.username.trim(),
            roles: form.roles,
        }
        if (form.password) {
            payload.password = form.password
        }

        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>
