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

import { rpc } from '@/api/request';
import type {
    BadgesType,
    MenuItemType,
    ProfileABCSType,
} from '@/api/types';
import { EventEmitter } from '@/utils/event';

const customMenuItems: MenuItemType[] = [];

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

let menuLoading = false;

interface MainPageStoreState {
    selectMenu: MenuItemType | null;
    badges: BadgesType;
    menu: MenuItemType[];
    profile: ProfileABCSType | null;
    initStarted: boolean;
    setSelectMenu: (menu: MenuItemType | null) => void;
    loadProfile: () => Promise<void>;
    //  saveProfile: (values: any) => Promise<void>;
    loadMenu: (silent?: boolean) => 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: (silent = false) => {
        if (menuLoading) {
            return;
        }
        menuLoading = true;
        rpc.menu()
            .then((data) => {
                if (!data?.result) {
                    return;
                }

                const updates: Partial<Pick<MainPageStoreState, 'menu' | 'badges' | 'selectMenu'>> = {};

                if (data.result.menu) {
                    updates.menu = [...data.result.menu, ...customMenuItems];
                }

                if (data.result.badges) {
                    updates.badges = data.result.badges;
                }

                if (!silent && data.result.allItems) {
                    const allItems = [...data.result.allItems, ...customMenuItems];
                    const currentSelectMenu = get().selectMenu;

                    const firstItem = allItems.find((item) => !item.single);

                    if (currentSelectMenu?.key) {
                        const item = allItems.find((item) => item.key === currentSelectMenu.key);
                        updates.selectMenu = item ?? firstItem ?? null;
                    } else {
                        const lastSelectMenuKey = localStorage.getItem('lastSelectMenuKey');
                        if (lastSelectMenuKey) {
                            const item = allItems.find((item) => item.key === lastSelectMenuKey);
                            updates.selectMenu = item && !item.single ? item : firstItem ?? null;
                        } else {
                            updates.selectMenu = firstItem ?? null;
                        }
                    }
                }

                if (Object.keys(updates).length > 0) {
                    set(updates);
                }
            })
            .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?.single && state.selectMenu?.key && state.selectMenu.key !== prev.selectMenu?.key) {
            localStorage.setItem('lastSelectMenuKey', state.selectMenu.key);
        }
    });

    EventEmitter.subscribe('updateMenu', () => {
        menuLoading = false;
        useMainPageStore.getState().loadMenu(true);
    });
}

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

export default useMainPageStore;
