<template>
    <dialog
        id="login_modal"
        ref="login_modal"
        @cancel.prevent=""
        @keyup="handleKeyPress"
        class="modal"
    >
        <div class="modal-box">
            <h3 class="text-3xl text-center mb-6">Connexion</h3>
            <div class="flex flex-wrap gap-5 justify-center">
                <template v-for="(user, index) in users" :key="user.id">
                    <LoginModalAvatar
                        :user="user"
                        :rank="index+1"
                        @selectUser="login"
                    />
                </template>
            </div>
        </div>
        <form method="dialog" class="modal-backdrop">
            <button class="cursor-default">close</button>
        </form>
    </dialog>
</template>

<script setup lang="ts">
    import type { User } from '~/types/user';

    const users: User[] = [
        { id: 1, name: 'John Doe', avatar: 'https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.webp' },
        { id: 2, name: 'Jane Doe', avatar: 'https://avatar.iran.liara.run/public' },
        { id: 3, name: 'Michel Moulin', avatar: '' },
        { id: 4, name: 'Jean Paris', avatar: '' },
        { id: 5, name: 'Marie Dupont', avatar: '' },
        { id: 6, name: 'Émilie Fournier', avatar: '' },
        { id: 7, name: 'Pierre Lefevre', avatar: '' },
        { id: 8, name: 'Sophie Lemoine', avatar: '' },
        { id: 9, name: 'Lucie Simon', avatar: '' },
        { id: 10, name: 'Kevin Boucher', avatar: '' },
    ];

    const loginModal = useTemplateRef('login_modal');

    const current_user = useCurrentUser();

    const login = (user: User) => {
        console.log('login', user);
        current_user.value = user;
        loginModal.value?.close();
    };

    const handleKeyPress = (event: KeyboardEvent) => {
        // Extract the rank from the event.code : Digit7 -> 7
        const rank = event.code.match(/\d/);
        if (!rank) {
            console.debug('Not handled key event', { event });
            return;
        }
        const user = getUserByRank(parseInt(rank[0]));
        if (user) {
            login(user);
        } else {
            console.debug('Not handled key event', { event });
        }
    };

    const getUserByRank = (rank: number): User => {
        return users[rank - 1];
    };
</script>