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

import VnInput from 'src/components/common/VnInput.vue';
import VnRow from 'components/ui/VnRow.vue';

import axios from 'axios';
import { useStateStore } from 'stores/useStateStore';
import useNotify from 'src/composables/useNotify.js';

const { t } = useI18n();
const route = useRoute();
const stateStore = useStateStore();
const { notify } = useNotify();

const initialData = ref({});
const formData = ref({
    forwardTo: null,
    account: null,
});

const hasAccount = ref(false);
const hasData = ref(false);
const loading = ref(false);
const hasDataChanged = computed(
    () =>
        formData.value.forwardTo !== initialData.value.forwardTo ||
        initialData.value.hasData !== hasData.value
);

const fetchAccountExistence = async () => {
    try {
        const { data } = await axios.get(`Accounts/${route.params.id}/exists`);
        return data.exists;
    } catch (error) {
        console.error('Error fetching account existence', error);
        return false;
    }
};

const fetchMailForwards = async () => {
    try {
        const response = await axios.get(`MailForwards/${route.params.id}`);
        return response.data;
    } catch (err) {
        console.error('Error fetching mail forwards', err);
        return null;
    }
};

const deleteMailForward = async () => {
    try {
        await axios.delete(`MailForwards/${route.params.id}`);
        formData.value.forwardTo = null;
        initialData.value.forwardTo = null;
        initialData.value.hasData = hasData.value;
        notify(t('globals.dataSaved'), 'positive');
    } catch (err) {
        console.error('Error deleting mail forward', err);
    }
};

const updateMailForward = async () => {
    try {
        await axios.patch('MailForwards', formData.value);
        initialData.value = { ...formData.value };
        initialData.value.hasData = hasData.value;
    } catch (err) {
        console.error('Error creating mail forward', err);
    }
};

const onSubmit = async () => {
    if (hasData.value) await updateMailForward();
    else await deleteMailForward();
};

const setInitialData = async () => {
    loading.value = true;
    initialData.value.account = route.params.id;
    formData.value.account = route.params.id;
    hasAccount.value = await fetchAccountExistence(route.params.id);
    if (!hasAccount.value) {
        loading.value = false;
        return;
    }

    const result = await fetchMailForwards(route.params.id);
    const forwardTo = result ? result.forwardTo : null;
    formData.value.forwardTo = forwardTo;
    initialData.value.forwardTo = forwardTo;

    initialData.value.hasData = hasAccount.value && !!forwardTo;
    hasData.value = hasAccount.value && !!forwardTo;
    loading.value = false;
};

watch(
    () => route.params.id,
    () => setInitialData()
);

onMounted(async () => await setInitialData());
</script>
<template>
    <div class="flex justify-center">
        <QSpinner v-if="loading" color="primary" size="md" />
        <QForm
            v-else-if="hasAccount"
            @submit="onSubmit()"
            class="full-width"
            style="max-width: 800px"
        >
            <Teleport to="#st-actions" v-if="stateStore?.isSubToolbarShown()">
                <div>
                    <QBtnGroup push class="q-gutter-x-sm">
                        <slot name="moreActions" />
                        <QBtn
                            color="primary"
                            icon="restart_alt"
                            flat
                            @click="reset()"
                            :label="t('globals.reset')"
                        />
                        <QBtn
                            color="primary"
                            icon="save"
                            @click="onSubmit()"
                            :disable="!hasDataChanged"
                            :label="t('globals.save')"
                        />
                    </QBtnGroup>
                </div>
            </Teleport>
            <QCard class="q-pa-lg">
                <VnRow class="row q-mb-md">
                    <QCheckbox
                        v-model="hasData"
                        :label="t('account.mailForwarding.enableMailForwarding')"
                        :toggle-indeterminate="false"
                    />
                </VnRow>
                <VnRow v-if="hasData" class="row q-gutter-md q-mb-md">
                    <VnInput
                        v-model="formData.forwardTo"
                        :label="t('account.mailForwarding.forwardingMail')"
                        :info="t('account.mailForwarding.mailInputInfo')"
                    >
                    </VnInput>
                </VnRow>
            </QCard>
        </QForm>
        <h5 v-else class="text-center">
            {{ t('account.mailForwarding.accountNotEnabled') }}
        </h5>
    </div>
</template>
