import React from 'react';
import { FatalErrorHandler } from './handlers/fatalErrorHandler';
import { OrgRedirectHandler } from './handlers/orgRedirectHandler';
import { SplashHandler } from './handlers/splashHandler';
import { PluginManager } from './pluginManager';
import type { SuiteInitResult, SuitePlugin, SuiteWrapper } from '../types';

interface WrapperHostProps<AppData> extends SuiteInitResult<AppData> {
    children: React.ReactNode;
    wrappers: SuiteWrapper<AppData>[];
}

function WrapperHost<AppData>(props: WrapperHostProps<AppData>) {
    const { wrappers, children, ...rest } = props;
    const [PluginWrapper] = wrappers;

    if (!PluginWrapper) return <>{children}</>;

    return (
        <WrapperHost {...rest} wrappers={wrappers.slice(1)}>
            <PluginWrapper {...rest}>{children}</PluginWrapper>
        </WrapperHost>
    );
}

interface SuiteAppWrapperProps<AppData> extends SuiteInitResult<AppData> {
    children?: React.ReactNode;
    plugins?: SuitePlugin<AppData>[];
}

export function SuiteAppWrapper<AppData>({
    plugins,
    children,
    ...rest
}: SuiteAppWrapperProps<AppData>) {
    const { highPriority, normalPriority } = PluginManager.getWrappers(plugins);

    const wrappers: SuiteWrapper<AppData>[] = [
        ...highPriority,
        OrgRedirectHandler,
        SplashHandler,
        FatalErrorHandler,
        ...normalPriority,
    ].reverse();

    return (
        <WrapperHost {...rest} wrappers={wrappers}>
            {children}
        </WrapperHost>
    );
}
