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

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

const $props = defineProps({
    allColumns: {
        type: Array,
        default: () => [],
    },
    tableCode: {
        type: String,
        default: '',
    },
    labelsTraductionsPath: {
        type: String,
        default: '',
    },
});

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

const { notify } = useNotify();
const state = useState();
const { t } = useI18n();
const popupProxyRef = ref(null);
const user = state.getUser();
const initialUserConfigViewData = ref(null);

const formattedCols = ref([]);

const areAllChecksMarked = computed(() => {
    return formattedCols.value.every((col) => col.active);
});

const setUserConfigViewData = (data) => {
    if (!data) return;
    // Importante: El name de las columnas de la tabla debe conincidir con el name de las variables que devuelve la view config
    formattedCols.value = $props.allColumns.map((col) => ({
        name: col,
        active: data[col] == undefined ? true : data[col],
    }));
    emitSavedConfig();
};

const toggleMarkAll = (val) => {
    formattedCols.value.forEach((col) => (col.active = val));
};

const getConfig = async (url, filter) => {
    const response = await axios.get(url, {
        params: { filter: filter },
    });
    return response.data && response.data.length > 0 ? response.data[0] : null;
};

const fetchViewConfigData = async () => {
    try {
        const userConfigFilter = {
            where: { tableCode: $props.tableCode, userFk: user.id },
        };
        const userConfig = await getConfig('UserConfigViews', userConfigFilter);

        if (userConfig) {
            initialUserConfigViewData.value = userConfig;
            setUserConfigViewData(userConfig.configuration);
            return;
        }

        const defaultConfigFilter = { where: { tableCode: $props.tableCode } };
        const defaultConfig = await getConfig('DefaultViewConfigs', defaultConfigFilter);

        if (defaultConfig) {
            setUserConfigViewData(defaultConfig.columns);
            return;
        }
    } catch (err) {
        console.err('Error fetching config view data', err);
    }
};

const saveConfig = async () => {
    try {
        const params = {};
        const configuration = {};

        formattedCols.value.forEach((col) => {
            const { name, active } = col;
            configuration[name] = active;
        });

        // Si existe una view config del usuario hacemos un update si no la creamos
        if (initialUserConfigViewData.value) {
            params.updates = [
                {
                    data: {
                        configuration: configuration,
                    },
                    where: {
                        id: initialUserConfigViewData.value.id,
                    },
                },
            ];
        } else {
            params.creates = [
                {
                    userFk: user.value.id,
                    tableCode: $props.tableCode,
                    tableConfig: $props.tableCode,
                    configuration: configuration,
                },
            ];
        }

        const response = await axios.post('UserConfigViews/crud', params);
        if (response.data && response.data[0]) {
            initialUserConfigViewData.value = response.data[0];
        }
        emitSavedConfig();
        notify('globals.dataSaved', 'positive');
        popupProxyRef.value.hide();
    } catch (err) {
        console.error('Error saving user view config', err);
    }
};

const emitSavedConfig = () => {
    const activeColumns = formattedCols.value
        .filter((col) => col.active)
        .map((col) => col.name);
    emit('onConfigSaved', activeColumns);
};

onMounted(async () => {
    await fetchViewConfigData();
});
</script>
<template>
    <QBtn color="primary" icon="view_column">
        <QPopupProxy ref="popupProxyRef">
            <QCard class="column q-pa-md">
                <QIcon name="info" size="sm" class="info-icon">
                    <QTooltip>{{ t('Check the columns you want to see') }}</QTooltip>
                </QIcon>
                <span class="text-body1 q-mb-sm">{{ t('Visible columns') }}</span>
                <QCheckbox
                    :label="t('Tick all')"
                    :model-value="areAllChecksMarked"
                    @update:model-value="toggleMarkAll($event)"
                    class="q-mb-sm"
                />
                <div
                    v-if="allColumns.length > 0 && formattedCols.length > 0"
                    class="checks-layout"
                >
                    <QCheckbox
                        v-for="(col, index) in allColumns"
                        :key="index"
                        :label="t(`${$props.labelsTraductionsPath + '.' + col}`)"
                        v-model="formattedCols[index].active"
                    />
                </div>
                <QBtn class="full-width q-mt-md" color="primary" @click="saveConfig()">{{
                    t('globals.save')
                }}</QBtn>
            </QCard>
        </QPopupProxy>
        <QTooltip>{{ t('Visible columns') }}</QTooltip>
    </QBtn>
</template>

<style lang="scss" scoped>
.info-icon {
    position: absolute;
    top: 20px;
    right: 20px;
}

.checks-layout {
    display: grid;
    grid-template-columns: repeat(3, 200px);
}
</style>

<i18n>
    es:
        Check the columns you want to see: Marca las columnas que quieres ver
        Visible columns: Columnas visibles
</i18n>
