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

import VnInputDate from 'components/common/VnInputDate.vue';
import VnInput from 'src/components/common/VnInput.vue';

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

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

const amountInputRef = ref(null);
const initialDated = Date.vnNew();
const unpaidClient = ref(false);
const isLoading = ref(false);
const amount = ref(null);
const dated = ref(initialDated);

const initialData = ref({
    dated: initialDated,
});

const hasChanged = computed(() => {
    return (
        initialData.value.dated !== dated.value ||
        initialData.value.amount !== amount.value
    );
});

onBeforeMount(() => {
    getData(route.params.id);
});

watch(
    () => route.params.id,
    (newValue) => {
        if (!newValue) return;
        getData(newValue);
    }
);

const getData = async (id) => {
    const filter = { where: { clientFk: id } };
    try {
        const { data } = await axios.get('ClientUnpaids', {
            params: { filter: JSON.stringify(filter) },
        });
        if (data.length) {
            setValues(data[0]);
        } else {
            defaultValues();
        }
    } catch (error) {
        defaultValues();
    }
};

const setValues = (data) => {
    unpaidClient.value = true;
    amount.value = data.amount;
    dated.value = data.dated;
    initialData.value = data;
};

const defaultValues = () => {
    unpaidClient.value = false;
    initialData.value.amount = null;
    setInitialData();
};

const setInitialData = () => {
    amount.value = initialData.value.amount;
    dated.value = initialData.value.dated;
};

const onSubmit = async () => {
    isLoading.value = true;

    const payload = {
        amount: amount.value,
        clientFk: route.params.id,
        dated: dated.value,
    };
    try {
        await axios.patch('ClientUnpaids', payload);
        notify('globals.dataSaved', 'positive');
        unpaidClient.value = true;
    } catch (error) {
        notify('errors.writeRequest', 'negative');
    } finally {
        isLoading.value = false;
    }
};

watch(
    () => unpaidClient.value,
    async (val) => {
        await nextTick();
        if (val) amountInputRef.value.focus();
    }
);
</script>

<template>
    <Teleport v-if="stateStore?.isSubToolbarShown()" to="#st-actions">
        <QBtnGroup push class="q-gutter-x-sm">
            <QBtn
                :disabled="!hasChanged"
                :label="t('globals.reset')"
                :loading="isLoading"
                @click="setInitialData"
                color="primary"
                flat
                icon="restart_alt"
                type="reset"
            />
            <QBtn
                :disabled="!hasChanged"
                :label="t('globals.save')"
                :loading="isLoading"
                @click="onSubmit"
                color="primary"
                icon="save"
            />
        </QBtnGroup>
    </Teleport>

    <div class="full-width flex justify-center">
        <QCard class="card-width q-pa-lg">
            <QForm>
                <VnRow>
                    <div class="col">
                        <QCheckbox :label="t('Unpaid client')" v-model="unpaidClient" />
                    </div>
                </VnRow>

                <VnRow class="row q-gutter-md q-mb-md" v-show="unpaidClient">
                    <div class="col">
                        <VnInputDate :label="t('Date')" v-model="dated" />
                    </div>
                    <div class="col">
                        <VnInput
                            ref="amountInputRef"
                            :label="t('Amount')"
                            clearable
                            type="number"
                            v-model="amount"
                            autofocus
                        >
                            <template #append>€</template></VnInput
                        >
                    </div>
                </VnRow>
            </QForm>
        </QCard>
    </div>
</template>

<i18n>
es:
    Unpaid client: Cliente impagado
    Date: Fecha
    Amount: Importe
</i18n>
