<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';

import CardList from 'src/components/ui/CardList.vue';
import VnSearchBar from 'src/components/ui/VnSearchBar.vue';

import { useAppStore } from 'stores/app';
import { storeToRefs } from 'pinia';
import { useUserStore } from 'stores/user';
import useNotify from 'src/composables/useNotify.js';

const { t } = useI18n();
const router = useRouter();
const userStore = useUserStore();
const appStore = useAppStore();
const { isHeaderMounted } = storeToRefs(appStore);
const { notify } = useNotify();

const loading = ref(false);
const users = ref([]);

const query = `SELECT u.id, u.name, u.nickname, u.active
            FROM account.user u
            WHERE u.name LIKE CONCAT('%', #user, '%')
            OR u.nickname LIKE CONCAT('%', #user, '%')
            OR u.id = #user
            ORDER BY u.name LIMIT 200`;

const onSearch = data => (users.value = data || []);

const supplantUser = async user => {
    try {
        await userStore.supplantUser(user);
        await appStore.getMenuLinks();
        router.push({ name: 'confirmedOrders' });
    } catch (error) {
        console.error('Error supplanting user:', error);
        notify(error.message, 'negative');
    }
};
</script>

<template>
    <Teleport v-if="isHeaderMounted" to="#actions">
        <VnSearchBar
            :sql-query="query"
            search-field="user"
            @on-search="onSearch"
            @on-search-error="users = []"
        />
    </Teleport>
    <QPage class="vn-w-xs">
        <QList class="flex justify-center">
            <span v-if="!loading && !users.length" class="flex items-center">
                <QIcon name="refresh" size="sm" class="q-mr-sm" />
                {{ t('noData') }}
            </span>
            <QSpinner
                v-if="loading"
                color="primary"
                size="3em"
                :thickness="2"
            />
            <CardList
                v-else
                v-for="(user, index) in users"
                :key="index"
                :clickable="false"
            >
                <template #content>
                    <span class="text-bold q-mb-sm">
                        {{ user.nickname }}
                    </span>
                    <span>#{{ user.id }} - {{ user.name }} </span>
                </template>
                <template #actions>
                    <QBtn
                        icon="people"
                        flat
                        rounded
                        @click="supplantUser(user.name)"
                        ><QTooltip>
                            {{ t('Impersonate user') }}
                        </QTooltip></QBtn
                    >
                </template>
            </CardList>
        </QList>
    </QPage>
</template>

<i18n lang="yaml">
en-US:
    User management: User management
    Disabled: Disabled
    Impersonate user: Impersonate user
    Access log: Access log
es-ES:
    User management: Gestión de usuarios
    Disabled: Desactivado
    Impersonate user: Suplantar usuario
    Access log: Registro de accesos
ca-ES:
    User management: Gestió d'usuaris
    Disabled: Deshabilitat
    Impersonate user: Suplantar usuari
    Access log: Registre d'accessos
fr-FR:
    User management: Gestion des utilisateurs
    Disabled: Désactivé
    Impersonate user: Accès utilisateur
    Access log: Journal des accès
pt-PT:
    User management: Gestão de usuarios
    Disabled: Desativado
    Impersonate user: Suplantar usuario
    Access log: Registro de acessos
</i18n>
