import React, { useState } from 'react';
import { AUTH_ERROR_CODES } from '@theorchard/suite-auth';
import { LoadingPageIndicator } from '@theorchard/suite-components';
import { clearRedirectFlag, getErrorCode, redirectToOrg } from '../../utils';
import type { SuiteWrapperProps } from '../../types';

/**
 * Determines whether the authenticated user is associated with a different brand/org.
 * If the user does not belong to the current site, we redirect to the correct one.
 */
export function OrgRedirectHandler<AppData>({
    children,
    error,
    data: { identity, config },
}: SuiteWrapperProps<AppData>) {
    const [redirecting, setRedirecting] = useState(false);

    if (redirecting) return <LoadingPageIndicator testId="WrongOrgRedirectIndicator" />;

    const isWrongOrg =
        config.wrongOrgRedirect &&
        ((error && getErrorCode(error) === AUTH_ERROR_CODES.WRONG_ORG) ||
            (identity && config.brand !== identity.defaultBrand));

    if (isWrongOrg) {
        const redirect = redirectToOrg({
            fromBrand: config.brand,
            toBrand: identity?.defaultBrand,
            environment: config.environment,
        });

        if (redirect) {
            setRedirecting(true);
            return null;
        }
    } else clearRedirectFlag();

    return <>{children}</>;
}
