import * as React from 'react';
import { Box, Spinner } from '@gluestack-ui/themed';
import { NavigationContainerComponent, ApplicationErrorHandler, ErrorBoundary } from '../../components';
import { PluginArea } from '@common-stack/client-react';
import routeConfigKeyReplace from '../../utils/routeConfigKeyReplace';
import { useLayoutSetting } from '../../hooks/useLayoutSetting';
let AppFeatures: any;
let AppLayout: any;

const ProLayout: React.FC<any> = (props) => {
    const [appRoutes, setAppRoutes] = React.useState<any>([]);
    const { pathKey, appLayout } = useLayoutSetting(props);
    AppLayout = appLayout;
    const { appFeatures } = routeConfigKeyReplace(pathKey, props?.features, appLayout);
    AppFeatures = appFeatures;

    React.useEffect(() => {
        if (appLayout) {
            let routes = AppFeatures ? AppFeatures?.getRoutes2('/', 'MainStack') || [] : null;
            setAppRoutes(routes);
        }
    }, [appLayout]);

    //const appRoutes = AppFeatures ? AppFeatures?.getRoutes2('/', 'MainStack') || [] : null;

    const loadingComponent = () => <Box flex={1}>{<Spinner />}</Box>;

    let plugins = AppFeatures?.getComponentFillPlugins() ?? props.features;
    let configuredRoutes = AppFeatures?.getConfiguredRoutes2('/') ?? props?.features?.getConfiguredRoutes2('/');
    if (!appRoutes) return loadingComponent();
    return (
        <ErrorBoundary>
            <NavigationContainerComponent configurableRoutes={configuredRoutes} independent={true}>
                {appRoutes}
                <PluginArea />
                <ApplicationErrorHandler plugins={plugins} />
            </NavigationContainerComponent>
        </ErrorBoundary>
    );
};

export { ProLayout, AppFeatures, AppLayout };
