<script setup>
    import { onMounted, ref } from 'vue';
    import Spiner from '../components/ui/Spiner.vue';
    import CardUser from '../components/CardUser.vue';
    import { useCompanyStore } from '../stores/company';
    import CreateUserModal from '../components/CreateUserModal.vue';
    import Pagination from '../components/Pagination.vue';
    import { useAuthStore } from '../stores/auth';
    import { useI18n } from 'vue-i18n';

    const companyStore = useCompanyStore();
    const authStore = useAuthStore();
    const { t } = useI18n()
    onMounted(() => {
        getInitData();
    });

    const currentUser = ref(null);
    const openModal = ref(false);
    const limit = 10;

    const getInitData = async() => {
        loading.value = true;
        await companyStore.getUsersCompany(limit);
        loading.value = false;
    }

    const getUsersByPage = async(data) => {
        loading.value = true;
        companyStore.usersCurrentPage = data.page
        await companyStore.getUsersCompany(limit, companyStore.usersCurrentPage, true);
        loading.value = false;
    }

    const loading = ref(false);

    const handleSetCurrentUser = (user) => {
        openModal.value = true;
        currentUser.value = user;
    }

    const handleResetCurrentUser = () => {
        openModal.value = false;
        currentUser.value = null;
    }

</script>

<template>
    <CreateUserModal
        v-if="openModal === true"
        :user="currentUser"
        @reset-user="handleResetCurrentUser"
    />
    <div>
        <h2 class="title mb-4">{{ t('global.users') }}</h2>
        <div class="btn-row mb-4">
            <button
                v-if="authStore.user?.job_role === 'owner' || authStore.user?.job_role === 'manager'"
                class="btn-primary-sm"
                data-toggle="modal" 
                data-target="#userModal"
                @click="handleSetCurrentUser(null)"
            >
                <i class="fa-solid fa-plus"></i> {{ t('buttons.addUser') }}
            </button>
        </div>
        <Spiner v-if="loading"/>
        <div v-else>
            <CardUser
                v-for="user in companyStore.users"
                :user="user"
                :readonly="false"
                @set-user="handleSetCurrentUser(user)"
            />
            <Pagination
                :limit="limit"
                :total="companyStore.usersTotal"
                :current-page="companyStore.usersCurrentPage"
                @get-elements="getUsersByPage"
            />
        </div>
    </div>
</template>

<style scoped>

</style>