import { useI18n } from 'vue-i18n';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { LocalStorage, useQuasar, Dark } from 'quasar';
import { Preferences } from 'src/modules/profile/models/preferences.models';
import { ProfileService } from 'src/modules/profile/services/profile-service';
import { RouteNames } from 'src/router/router-constants';


export const useUiStore = defineStore('ui', () => {
    const q = useQuasar();
    const { locale } = useI18n();
    const is_left_drawer_open = ref(true);
    const focus_next_component = ref(false);
    const is_mobile_mode = computed(() => q.screen.lt.md);
    const user_preferences = ref<Preferences>(new Preferences);
    const current_page = ref<RouteNames>(RouteNames.DASHBOARD);


    const toggleRightDrawer = () => {
        is_left_drawer_open.value = !is_left_drawer_open.value;
    };

    const getUserPreferences = async () => {
        try {
            const local_user_preferences = LocalStorage.getItem<Preferences>('user_preferences');

            if (local_user_preferences !== null) {
                if (local_user_preferences.id !== -1) {
                    Object.assign(user_preferences.value, local_user_preferences);
                    setPreferences();
                    return;
                }
            }

            const response = await ProfileService.getUserPreferences();

            if (response.success && response.data) {
                LocalStorage.setItem('user_preferences', response.data);
                Object.assign(user_preferences.value, response.data);
                setPreferences();
            }
        } catch (error) {
            user_preferences.value = new Preferences;
            console.error('Could not retrieve user preferences: ', error);
        }
    };

    const updateUserPreferences = async () => {
        try {
            if (user_preferences.value.id === -1) return;

            const response = await ProfileService.updateUserPreferences(user_preferences.value);
            if (response.success && response.data) {
                Object.assign(user_preferences.value, response.data);
                LocalStorage.setItem('user_preferences', response.data);
                setPreferences();
                return;
            }
        } catch (error) {
            console.error('Could not update user preferences: ', error);
        }
    };

    const setPreferences = () => {
        if (user_preferences.value !== undefined) {
            // if user_preferences.value.is_dark_mode === null
            Dark.set(user_preferences.value.is_dark_mode ?? "auto");
            locale.value = user_preferences.value.display_language;
        }
    }

    return {
        current_page,
        is_mobile_mode,
        focus_next_component,
        is_left_drawer_open,
        user_preferences,
        toggleRightDrawer,
        getUserPreferences,
        updateUserPreferences,
    };
});
