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

import VnPaginate from 'src/components/ui/VnPaginate.vue';
import VnSearchbar from 'components/ui/VnSearchbar.vue';
import VnLv from 'src/components/ui/VnLv.vue';
import CardList from 'src/components/ui/CardList.vue';
import AccountSummary from './Card/AccountSummary.vue';
import AccountFilter from './AccountFilter.vue';
import AccountCreate from './AccountCreate.vue';

import { useSummaryDialog } from 'src/composables/useSummaryDialog';
import { useStateStore } from 'stores/useStateStore';
import { useRole } from 'src/composables/useRole';
import { QDialog } from 'quasar';

const stateStore = useStateStore();
const router = useRouter();
const { t } = useI18n();
const { viewSummary } = useSummaryDialog();
const accountCreateDialogRef = ref(null);
const showNewUserBtn = computed(() => useRole().hasAny(['itManagement']));

const filter = {
    fields: ['id', 'nickname', 'name', 'role'],
    include: { relation: 'role', scope: { fields: ['id', 'name'] } },
};

const exprBuilder = (param, value) => {
    switch (param) {
        case 'search':
            return /^\d+$/.test(value)
                ? { id: value }
                : {
                      or: [
                          { name: { like: `%${value}%` } },
                          { nickname: { like: `%${value}%` } },
                      ],
                  };
        case 'name':
        case 'nickname':
            return { [param]: { like: `%${value}%` } };
        case 'roleFk':
            return { [param]: value };
    }
};

const getApiUrl = () => new URL(window.location).origin;

const navigate = (event, id) => {
    if (event.ctrlKey || event.metaKey)
        return window.open(`${getApiUrl()}/#/account/${id}/summary`);
    router.push({ path: `/account/${id}` });
};

const openCreateModal = () => accountCreateDialogRef.value.show();
</script>

<template>
    <template v-if="stateStore.isHeaderMounted()">
        <Teleport to="#searchbar">
            <VnSearchbar
                data-key="AccountList"
                url="VnUsers/preview"
                :expr-builder="exprBuilder"
                :label="t('account.search')"
                :info="t('account.searchInfo')"
            />
        </Teleport>
        <Teleport to="#actions-append">
            <div class="row q-gutter-x-sm">
                <QBtn
                    flat
                    @click="stateStore.toggleRightDrawer()"
                    round
                    dense
                    icon="menu"
                >
                    <QTooltip bottom anchor="bottom right">
                        {{ t('globals.collapseMenu') }}
                    </QTooltip>
                </QBtn>
            </div>
        </Teleport>
    </template>
    <QDrawer v-model="stateStore.rightDrawer" side="right" :width="256" show-if-above>
        <QScrollArea class="fit text-grey-8">
            <AccountFilter data-key="AccountList" :expr-builder="exprBuilder" />
        </QScrollArea>
    </QDrawer>
    <QPage class="column items-center q-pa-md">
        <div class="vn-card-list">
            <VnPaginate
                :filter="filter"
                data-key="AccountList"
                url="VnUsers/preview"
                auto-load
            >
                <template #body="{ rows }">
                    <CardList
                        v-for="row of rows"
                        :id="row.id"
                        :key="row.id"
                        :title="row.nickname"
                        @click="navigate($event, row.id)"
                    >
                        <template #list-items>
                            <VnLv :label="t('account.card.name')" :value="row.nickname">
                            </VnLv>
                            <VnLv
                                :label="t('account.card.nickname')"
                                :value="row.username"
                            >
                            </VnLv>
                        </template>
                        <template #actions>
                            <QBtn
                                :label="t('components.smartCard.openSummary')"
                                @click.stop="viewSummary(row.id, AccountSummary)"
                                color="primary"
                                style="margin-top: 15px"
                            />
                        </template>
                    </CardList>
                </template>
            </VnPaginate>
        </div>
        <QDialog
            ref="accountCreateDialogRef"
            transition-hide="scale"
            transition-show="scale"
        >
            <AccountCreate />
        </QDialog>
        <QPageSticky :offset="[20, 20]" v-if="showNewUserBtn">
            <QBtn @click="openCreateModal" color="primary" fab icon="add" />
            <QTooltip class="text-no-wrap">
                {{ t('account.card.newUser') }}
            </QTooltip>
        </QPageSticky>
    </QPage>
</template>
