import type { FC } from 'react';
import React, { useContext } from 'react';
import { ENV_PROD } from '@theorchard/constants';
import { AuthClientContext } from '@theorchard/suite-auth';
import { Button, ErrorMessage } from '@theorchard/suite-components';
import { useAppConfig } from '@theorchard/suite-config';
import { formatMessage } from '@theorchard/suite-i18n';
import { IdentityContext } from '@theorchard/suite-identity';
import { Page } from '../../components/page';
import { clearAppStorage } from '../../utils';
import type { AuthClient } from '@theorchard/suite-auth';
import type { Identity } from '@theorchard/suite-identity';

export interface Props {
    error: Error;
    identity?: Identity;
    client?: AuthClient;
    history: History;
    location: Location;
}

const CLASSNAME = 'ErrorPage';

export const ErrorPage: FC<Props> = ({ client, history, location, error }) => {
    const { environment } = useAppConfig();
    const handleRetry = () => {
        clearAppStorage();

        history.replaceState({}, document.title, location.pathname);
        location.reload();
    };

    return (
        <Page className={CLASSNAME} testId={CLASSNAME}>
            <ErrorMessage code="generic" illustration="error" />
            {environment !== ENV_PROD && <p className={`${CLASSNAME}-details`}>{error.message}</p>}
            <div className={`${CLASSNAME}-actions`}>
                <Button onClick={handleRetry}>{formatMessage('error_retry')}</Button>
                {client && (
                    <Button onClick={async () => await client.logout()}>
                        {formatMessage('error_backToLogin')}
                    </Button>
                )}
            </div>
        </Page>
    );
};

export const ErrorPageContainer: FC<{ error: Error }> = ({ error }) => {
    const { authClient } = useContext(AuthClientContext);
    const { identity } = useContext(IdentityContext);

    return (
        <ErrorPage
            history={window.history}
            location={window.location}
            error={error}
            client={authClient}
            identity={identity}
        />
    );
};
