import {
    createContext,
    type ReactNode,
    useContext,
    useEffect,
    useRef,
    useState,
} from 'react';

import { rpcCache } from '@/api/cache';
import { rpc } from '@/api/request';
import {
    MenuItemType,
    ProfileBCDSType,
} from '@/api/types';
import { toast } from '@/components/ToastRoot';
import { useAppConfig } from '@/contexts/AppConfigContext';
import { Lang } from '@/lang/Lang';

interface MainPageContextType {
    selectMenu: MenuItemType | null;
    setSelectMenu: (menu: MenuItemType | null) => void;
    menu: MenuItemType[];
    profile: ProfileBCDSType | null;
    saveProfile: (values: any) => Promise<void>;
}

const MainPageContext = createContext<MainPageContextType | undefined>(
    undefined,
);

interface MainPageProviderProps {
    children: ReactNode;
    initialMenu?: string;
}

export function MainPageProvider({
    children,
}: MainPageProviderProps) {
    const [selectMenu, setSelectMenu] = useState<MenuItemType | null>(null);

    const { isMobile } = useAppConfig();

    const [menu, setMenu] = useState<MenuItemType[]>([]);

    const [allKeys, setAllKeys] = useState<MenuItemType[]>([]);

    const [profile, setProfile] = useState<ProfileBCDSType | null>(null);



    useEffect(() => {
        loadProfile();
    }, []);

    useEffect(() => {

        if (selectMenu?.key) {
            localStorage.setItem("lastSelectMenuKey", selectMenu?.key)
        }

    }, [selectMenu])

    const loadProfile = () => {
        rpc.profile().then((data) => {
            if (data?.result) {
                setProfile(data.result ?? null);
            }
        });
    }

    const saveProfile = (values: any): Promise<void> => {
        return new Promise((resolve, reject) => {

            let loading = toast.loading(Lang.key('saving_profile'));
            rpc.updateProfile({
                values: values
            }).then(() => {
                loadProfile();
                resolve();
                toast.success(Lang.key('profile_saved_successfully'));
            }).catch((error) => {
                toast.error(Lang.key('error_saving_profile'));
                reject(error);
            }).finally(() => {
                toast.dismiss(loading);
            });
        });
    }

    const menuLoading = useRef(false);


    const customMenuItems: MenuItemType[] = [];

    /*[
        {
            label: Lang.key('bi_view'),
            key: 'bi_view',
            icon: 'chart-box-outline',

        }
    ];*/

    useEffect(() => {
        if (menuLoading.current) {
            return;
        }
        menuLoading.current = true;
        rpcCache.menu().then((data) => {
            if (data?.result) {
                if (data.result.menu) {
                    setMenu([...data.result.menu, ...customMenuItems]);
                }
                if (data.result.allItems) {

                    data.result.allItems = [...data.result.allItems, ...customMenuItems];



                    setAllKeys(data.result.allItems);




                    if (selectMenu) {
                        const item = data.result.allItems.find((item) => item.key === selectMenu);
                        if (item) {
                            setSelectMenu(item);
                        } else {
                            setSelectMenu(data.result.allItems[0] || null);
                        }
                    } else {

                        const lastSelectMenuKey = localStorage.getItem("lastSelectMenuKey");
                        if (lastSelectMenuKey) {
                            const item = data.result.allItems.find((item) => item.key === lastSelectMenuKey);
                            if (item) {
                                setSelectMenu(item);
                            } else {
                                setSelectMenu(data.result.allItems[0] || null);
                            }
                        } else {

                            setSelectMenu(data.result.allItems[0] || null);
                        }
                    }


                }


            }
        }).finally(() => {
            menuLoading.current = false;
        });
    }, []);

    const value: MainPageContextType = {
        selectMenu,
        setSelectMenu,
        menu,
        profile,
        saveProfile
    };

    return (
        <MainPageContext.Provider value={value}>
            {children}
        </MainPageContext.Provider>
    );
}

export function useMainPage(): MainPageContextType {
    const context = useContext(MainPageContext);
    if (context === undefined) {
        throw new Error('useMainPage must be used within a MainPageProvider');
    }
    return context;
}

