<script setup>
import axios from 'axios';
import { computed, onMounted, ref, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useRoute } from 'vue-router';
import { useAcl } from 'src/composables/useAcl';
import { useArrayData } from 'src/composables/useArrayData';
import { useState } from 'src/composables/useState';
import VnConfirm from 'src/components/ui/VnConfirm.vue';
import VnInputPassword from 'src/components/common/VnInputPassword.vue';
import VnChangePassword from 'src/components/common/VnChangePassword.vue';
import { useQuasar } from 'quasar';
import { useRouter } from 'vue-router';
import VnCheckbox from 'src/components/common/VnCheckbox.vue';

const $props = defineProps({
    hasAccount: {
        type: Boolean,
        default: false,
        required: true,
    },
});

const { t } = useI18n();
const { hasAccount } = toRefs($props);
const { openConfirmationModal } = useVnConfirm();
const arrayData = useArrayData('Account');
const route = useRoute();
const router = useRouter();
const state = useState();
const user = state.getUser();
const { notify } = useQuasar();
const account = computed(() => arrayData.store.data);
account.value.hasAccount = hasAccount.value;
const entityId = computed(() => +route.params.id);
const hasitManagementAccess = ref();
const hasSysadminAccess = ref();
const isHimself = computed(() => user.value.id === account.value.id);
const url = computed(() =>
    isHimself.value
        ? 'Accounts/change-password'
        : `Accounts/${entityId.value}/setPassword`,
);

async function updateStatusAccount(active) {
    if (active) {
        await axios.post(`Accounts`, { id: entityId.value });
    } else {
        await axios.delete(`Accounts/${entityId.value}`);
    }

    account.value.hasAccount = active;
    const status = active ? 'enable' : 'disable';
    notify({
        message: t(`account.card.actions.${status}Account.success`),
        type: 'positive',
    });
}
async function updateStatusUser(active) {
    await axios.patch(`VnUsers/${entityId.value}`, { active });
    account.value.active = active;
    const status = active ? 'activate' : 'deactivate';
    notify({
        message: t(`account.card.actions.${status}User.success`),
        type: 'positive',
    });
}

async function deleteAccount() {
    const { data } = await axios.delete(`VnUsers/${entityId.value}`);
    if (data) {
        notify({
            message: t('account.card.actions.delete.success'),
            type: 'positive',
        });
        router.push({ name: 'AccountList' });
    }
}
const showSyncDialog = ref(false);
const syncPassword = ref(null);
const shouldSyncPassword = ref(false);
async function sync() {
    const params = { force: true };
    if (shouldSyncPassword.value) params.password = syncPassword.value;
    await axios.patch(`Accounts/${account.value.name}/sync`, {
        params,
    });
    notify({
        message: t('account.card.actions.sync.success'),
        type: 'positive',
    });
}
const askOldPass = ref(false);
const changePassRef = ref();

const onChangePass = (oldPass) => {
    askOldPass.value = oldPass;
    changePassRef.value.show();
};

onMounted(() => {
    hasitManagementAccess.value = useAcl().hasAny([
        { model: 'VnUser', props: 'higherPrivileges', accessType: 'WRITE' },
    ]);
    hasSysadminAccess.value = useAcl().hasAny([
        { model: 'VnUser', props: 'adminUser', accessType: 'WRITE' },
    ]);
});
</script>
<template>
    <VnChangePassword
        ref="changePassRef"
        :ask-old-pass="askOldPass"
        :submit-fn="
            async (newPassword, oldPassword) => {
                const body = isHimself ? { userId: entityId, oldPassword } : {};
                await axios.patch(url, { ...body, newPassword });
            }
        "
    />
    <VnConfirm
        v-model="showSyncDialog"
        :message="t('account.card.actions.sync.message')"
        :title="t('account.card.actions.sync.title')"
        :promise="sync"
    >
        <template #customHTML>
            <VnCheckbox
                v-model="shouldSyncPassword"
                :label="t('account.card.actions.sync.checkbox')"
                :info="t('account.card.actions.sync.tooltip')"
                clearable
                clear-icon="close"
                color="primary"
            />
            <VnInputPassword
                v-if="shouldSyncPassword"
                :label="t('login.password')"
                v-model="syncPassword"
                class="full-width"
                clearable
                clear-icon="close"
                type="password"
            />
        </template>
    </VnConfirm>
    <QItem
        v-if="hasitManagementAccess"
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('account.card.actions.disableAccount.title'),
                t('account.card.actions.disableAccount.subtitle'),
                () => deleteAccount(),
                () => deleteAccount(),
            )
        "
    >
        <QItemSection>{{ t('globals.delete') }}</QItemSection>
    </QItem>
    <QItem v-if="hasSysadminAccess || isHimself" v-ripple clickable>
        <QItemSection @click="onChangePass(isHimself)">
            {{ isHimself ? t('globals.changePass') : t('globals.setPass') }}
        </QItemSection>
    </QItem>
    <QItem
        v-if="!account.hasAccount && hasSysadminAccess"
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('account.card.actions.enableAccount.title'),
                t('account.card.actions.enableAccount.subtitle'),
                () => updateStatusAccount(true),
                () => updateStatusAccount(true),
            )
        "
    >
        <QItemSection>{{ t('account.card.actions.enableAccount.name') }}</QItemSection>
    </QItem>
    <QItem
        v-if="account.hasAccount && hasSysadminAccess"
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('account.card.actions.disableAccount.title'),
                t('account.card.actions.disableAccount.subtitle'),
                () => updateStatusAccount(false),
                () => updateStatusAccount(false),
            )
        "
    >
        <QItemSection>{{ t('account.card.actions.disableAccount.name') }}</QItemSection>
    </QItem>

    <QItem
        v-if="!account.active && hasitManagementAccess"
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('account.card.actions.activateUser.title'),
                t('account.card.actions.activateUser.title'),
                () => updateStatusUser(true),
                () => updateStatusUser(true),
            )
        "
    >
        <QItemSection>{{ t('account.card.actions.activateUser.name') }}</QItemSection>
    </QItem>
    <QItem
        v-if="account.active && hasitManagementAccess"
        v-ripple
        clickable
        @click="
            openConfirmationModal(
                t('account.card.actions.deactivateUser.title'),
                t('account.card.actions.deactivateUser.title'),
                () => updateStatusUser(false),
                () => updateStatusUser(false),
            )
        "
    >
        <QItemSection>{{ t('account.card.actions.deactivateUser.name') }}</QItemSection>
    </QItem>
    <QItem
        v-if="useAcl().hasAny([{ model: 'VnRole', props: '*', accessType: 'WRITE' }])"
        v-ripple
        clickable
        @click="showSyncDialog = true"
    >
        <QItemSection>{{ t('account.card.actions.sync.name') }}</QItemSection>
    </QItem>
    <QSeparator />
</template>
