import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';

import { rpcCache } from '@/api/cache';
import { rpc } from '@/api/request';
import type {
    MenuItemType,
    ProfileABDTType,
} from '@/api/types';
import { toast } from '@/componentsRoot/ToastRoot';
import { Lang } from '@/lang/Lang';

const customMenuItems: MenuItemType[] = [];

const initialState = {
    selectMenu: null as MenuItemType | null,
    menu: [] as MenuItemType[],
    profile: null as ProfileABDTType | null,
    initStarted: false,
};

let menuLoading = false;

interface MainPageStoreState {
    selectMenu: MenuItemType | null;
    menu: MenuItemType[];
    profile: ProfileABDTType | null;
    initStarted: boolean;
    setSelectMenu: (menu: MenuItemType | null) => void;
    loadProfile: () => Promise<void>;
    saveProfile: (values: any) => Promise<void>;
    loadMenu: () => void;
    init: () => void;
    reset: () => void;
}

const useMainPageStore = create<MainPageStoreState>((set, get) => ({
    ...initialState,

    setSelectMenu: (menu) => set({ selectMenu: menu }),

    loadProfile: () => {
        return new Promise((resolve, reject) => {
            rpc.profile().then((data) => {
                if (data?.result) {
                    set({ profile: data.result ?? null });

                }
            }).finally(() => {
                resolve();
            });
        });
    },

    saveProfile: (values) => {
        return new Promise((resolve, reject) => {
            const loading = toast.loading(Lang.key('saving_profile'));
            rpc.updateProfile({ values })
                .then(() => {
                    get().loadProfile();
                    resolve();
                    toast.success(Lang.key('profile_saved_successfully'));
                })
                .catch((error) => {
                    toast.error(Lang.key('error_saving_profile'));
                    reject(error);
                })
                .finally(() => {
                    toast.dismiss(loading);
                });
        });
    },

    loadMenu: () => {
        if (menuLoading) {
            return;
        }
        menuLoading = true;
        rpcCache.menu()
            .then((data) => {
                if (data?.result) {
                    if (data.result.menu) {
                        set({ menu: [...data.result.menu, ...customMenuItems] });
                    }
                    if (data.result.allItems) {
                        const allItems = [...data.result.allItems, ...customMenuItems];
                        const selectMenu = get().selectMenu;

                        if (selectMenu) {
                            const item = allItems.find((item) => item.key === selectMenu);
                            if (item) {
                                set({ selectMenu: item });
                            } else {
                                set({ selectMenu: allItems[0] || null });
                            }
                        } else {
                            const lastSelectMenuKey = localStorage.getItem('lastSelectMenuKey');
                            if (lastSelectMenuKey) {
                                const item = allItems.find((item) => item.key === lastSelectMenuKey);
                                if (item) {
                                    set({ selectMenu: item });
                                } else {
                                    set({ selectMenu: allItems[0] || null });
                                }
                            } else {
                                set({ selectMenu: allItems[0] || null });
                            }
                        }
                    }
                }
            })
            .finally(() => {
                menuLoading = false;
            });
    },

    init: () => {
        if (get().initStarted) {
            return;
        }
        set({ initStarted: true });
        get().loadProfile();
        get().loadMenu();
    },

    reset: () => {
        menuLoading = false;
        set({ ...initialState });
    },
}));

if (typeof window !== 'undefined') {
    useMainPageStore.subscribe((state, prev) => {
        if (state.selectMenu?.key && state.selectMenu.key !== prev.selectMenu?.key) {
            localStorage.setItem('lastSelectMenuKey', state.selectMenu.key);
        }
    });
}

export function useMainPage() {
    return useMainPageStore(
        useShallow((s) => ({
            selectMenu: s.selectMenu,
            setSelectMenu: s.setSelectMenu,
            menu: s.menu,
            profile: s.profile,
            loadProfile: s.loadProfile,
            saveProfile: s.saveProfile,
        })),
    );
}

export default useMainPageStore;
