<template>
    <form @submit.prevent="validate">
        <div
            class="flex items-center justify-between gap-10">
            <h1 class="text-3xl font-bold uppercase">
                {{ userId ? "Modification de l'utilisateur" : "Ajout d'un utilisateur" }}
            </h1>
            <UiButton
                class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
                type="submit"
            >
                <Icon :name="userId ? '' : 'mdi:plus'" size="28" />
                {{ userId ? 'Valider' : 'Ajouter' }}
            </UiButton>
        </div>

        <div class="grid gap-y-16 gap-x-40 py-12">
            <UiTextInput
                id="user-name"
                v-model="form.username"
                label="Nom de l'utilisateur"
            />

            <UiSelect
                id="user-role"
                v-model="form.role"
                label="Rôle de l'utilisateur"
                :options="ROLE"
            />
            <UiTextInput
                id="user-password"
                v-model="form.password"
                label="Mot de passe"
                type="password"

            />

        </div>
    </form>
</template>
<script setup lang="ts">
import {computed, reactive, ref, watch} from 'vue'
import {ROLE} from '~/utils/constants'
import {createUser, updateUser, getUser} from '~/services/auth'
import type {UserData, UserFormData, UserPayload} from '~/services/dto/user-data'

const route = useRoute()
const router = useRouter()
const userId = computed(() => resolveUserId(route.params.id))
const isLoading = ref(false)
const isHydrating = ref(false)

const resolveUserId = (param: unknown) => {
    const idStr = Array.isArray(param) ? param[0] : param
    if (!idStr) {
        return null
    }
    const id = Number(idStr)
    return Number.isFinite(id) ? id : null
}


const form = reactive<UserFormData>({
    username: '',
    password: '',
    role: ''
})

const hydrateFromUser = (user: UserData | null) => {
    if (!user) {
        return
    }
    isHydrating.value = true
    form.username = user.username ?? ''
    const roles = user.roles ?? []
    const hasAdmin = roles.includes("ROLE_ADMIN")
    form.role = hasAdmin ? "ROLE_ADMIN" : "ROLE_USER"
    form.password = ''
    isHydrating.value = false
}

watch(
    () => userId.value,
    async (id) => {
        if (id === null) {
            return
        }
        isLoading.value = true
        try {
            const user = await getUser(id)
            hydrateFromUser(user)
        } finally {
            isLoading.value = false
        }
    },
    {immediate: true}
)

async function validate() {

    const normalizedUsername = form.username.trim()
    const normalizedRole = form.role.trim()
    const normalizedPassword = form.password.trim()

    const basePayload: UserPayload = {
        username: normalizedUsername,
        roles: normalizedRole ? [normalizedRole] : undefined,
    }
    if (normalizedPassword) {
        basePayload.password = normalizedPassword
    }

    if (userId.value) {
        await updateUser(userId.value, basePayload)
        await router.push(`/admin/user/list/`)
        return
    }

    const created = await createUser(basePayload)
    if (created) {
        await router.push(`/admin/user/list/`)
    }
}
</script>
