<script setup>
import axios from 'axios';
import { onMounted, onUnmounted, computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { useState } from 'src/composables/useState';
import { useStateStore } from 'stores/useStateStore';
import { useValidator } from 'src/composables/useValidator';
import SkeletonForm from 'components/ui/SkeletonForm.vue';

const quasar = useQuasar();
const state = useState();
const stateStore = useStateStore();
const { t } = useI18n();
const { validate } = useValidator();

const $props = defineProps({
    url: {
        type: String,
        default: '',
    },
    model: {
        type: String,
        default: '',
    },
    filter: {
        type: Object,
        default: null,
    },
    urlUpdate: {
        type: String,
        default: null,
    },
    defaultActions: {
        type: Boolean,
        default: true,
    },
});

const emit = defineEmits(['onFetch']);

defineExpose({
    save,
});

onMounted(async () => await fetch());

onUnmounted(() => {
    state.unset($props.model);
});

const isLoading = ref(false);
const hasChanges = ref(false);
const originalData = ref();
const formData = computed(() => state.get($props.model));
const formUrl = computed(() => $props.url);

function tMobile(...args) {
    if (!quasar.platform.is.mobile) return t(...args);
}

async function fetch() {
    const { data } = await axios.get($props.url, {
        params: { filter: $props.filter },
    });

    state.set($props.model, data);
    originalData.value = Object.assign({}, data);

    watch(formData.value, () => (hasChanges.value = true));

    emit('onFetch', state.get($props.model));
}

async function save() {
    if (!hasChanges.value) {
        return quasar.notify({
            type: 'negative',
            message: t('globals.noChanges'),
        });
    }
    isLoading.value = true;
    await axios.patch($props.urlUpdate || $props.url, formData.value);

    originalData.value = formData.value;
    hasChanges.value = false;
    isLoading.value = false;
}

function reset() {
    state.set($props.model, originalData.value);
    hasChanges.value = false;
}
// eslint-disable-next-line vue/no-dupe-keys
function filter(value, update, filterOptions) {
    update(
        () => {
            const { options, filterFn } = filterOptions;

            options.value = filterFn(options, value);
        },
        (ref) => {
            ref.setOptionIndex(-1);
            ref.moveOptionSelection(1, true);
        }
    );
}

watch(formUrl, async () => {
    originalData.value = null;
    reset();
    fetch();
});
</script>
<template>
    <QBanner v-if="hasChanges" class="text-white bg-warning">
        <QIcon name="warning" size="md" class="q-mr-md" />
        <span>{{ t('globals.changesToSave') }}</span>
    </QBanner>
    <QForm v-if="formData" @submit="save" @reset="reset" class="q-pa-md">
        <slot name="form" :data="formData" :validate="validate" :filter="filter"></slot>
    </QForm>
    <Teleport to="#st-actions" v-if="stateStore.isSubToolbarShown()">
        <div v-if="$props.defaultActions">
            <QBtnGoup push class="q-gutter-x-sm">
                <slot name="moreActions" />
                <QBtn
                    :label="tMobile('globals.reset')"
                    color="primary"
                    icon="restart_alt"
                    flat
                    @click="reset"
                    :disable="!hasChanges"
                    :title="t('globals.reset')"
                />
                <QBtn
                    :label="tMobile('globals.save')"
                    color="primary"
                    icon="save"
                    @click="save"
                    :disable="!hasChanges"
                    :title="t('globals.save')"
                />
            </QBtnGoup>
        </div>
    </Teleport>
    <SkeletonForm v-if="!formData" />
    <QInnerLoading
        :showing="isLoading"
        :label="t('globals.pleaseWait')"
        color="primary"
    />
</template>
