import React, {
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';

import ChannelPage from '../pages/ChannelPage/ChannelPage';
import LoadingPage from '../pages/LoadingPage/LoadingPage';
import LoginPage from '../pages/LoginPage/LoginPage';
import MainPage from '../pages/MainPage/MainPage';

export const goBack = () => {
    routerRootRef.current?.goBack();
}



export type ChannelPageProps = {
    channelID: string;
}

export const ROUTER = (): { [key: string]: { component: React.ComponentType<any>, move: (props: any) => void } } => {
    return {
        "LoadingPage": {
            component: LoadingPage,
            move: (props: any) => {
                routerRootRef.current?.onChanceRoute('LoadingPage', props);
            }
        },
        "LoginPage": {
            component: LoginPage,
            move: (props: any) => {
                routerRootRef.current?.onChanceRoute('LoginPage', props);
            }
        },
        "MainPage": {
            component: MainPage,
            move: (props: any) => {
                routerRootRef.current?.onChanceRoute('MainPage', props);
            }
        },
        "ChannelPage": {
            component: ChannelPage,
            move: (props: ChannelPageProps) => {
                routerRootRef.current?.onChanceRoute('ChannelPage', props);
            }
        },

    }

};




export const routerRootRef = React.createRef<RouterRootRef>();

type RouterRootRef = {
    onChanceRoute: (route: string, props?: any) => void;
    goBack: () => void;
}


export const RouterRoot = React.forwardRef<RouterRootRef, any>((props, ref) => {


    const screenIdCounterRef = useRef<number>(0);

    useImperativeHandle(ref, () => ({
        goBack: () => {

            // Просто удаляем последний экран из renderScreen, не пересоздавая остальные
            setRenderScreen((prev) => {
                return prev.slice(0, -1);
            });
        },
        onChanceRoute: (route: string, props?: any) => {


            if (renderScreen[renderScreen.length - 1]?.route === route) {
                return;
            }




            setRenderScreen((prev) => {
                // Создаем новый экран с уникальным ID для правильного отслеживания React
                const newScreen = {
                    route,
                    props,
                    id: screenIdCounterRef.current++
                };

                // Добавляем новый экран
                let newRenderScreen = [...prev, newScreen];


                return newRenderScreen;

            });





        }
    }));


    const [renderScreen, setRenderScreen] = useState<{ route: string, props?: any, id: number }[]>([]);
    const [isInitialized, setIsInitialized] = useState(false);

    useEffect(() => {




        setRenderScreen([
            { route: 'LoadingPage', props: {}, id: screenIdCounterRef.current++ }
        ]);

        setIsInitialized(true);
    }, []);

    useEffect(() => {


        // Сохраняем только после инициализации, чтобы не перезаписать данные при первом рендере
        if (!isInitialized) {
            return;
        }



        if (renderScreen.length == 0) {
            setRenderScreen([
                { route: 'LoadingPage', props: {}, id: screenIdCounterRef.current++ }
            ]);
            return;
        }


    }, [renderScreen, isInitialized]);





    return <>

        {renderScreen.map((screen, index) => {

            let screenComponent = ROUTER()[screen.route as keyof typeof ROUTER];


            if (!screenComponent) {
                return null;
            }

            if (index == renderScreen.length - 1) {
                return <screenComponent.component key={screen.id} {...screen.props} />
            }



        })}
    </>



});