import React from 'react';
import { ErrorMessage } from '@theorchard/suite-components';
import { Sentry } from '@theorchard/suite-frontend';
import { formatMessage } from '../../utils';

interface ErrorBoundaryProps {
    children?: React.ReactNode;
}

interface ErrorBoundaryState {
    error: Error | null;
}

export class ErrorBoundary extends React.Component<
    ErrorBoundaryProps,
    ErrorBoundaryState
> {
    state: ErrorBoundaryState = { error: null };

    static getDerivedStateFromError(error: Error): ErrorBoundaryState {
        return { error };
    }

    componentDidCatch(error: Error): void {
        Sentry.captureException(error);
        this.setState({ error });
    }

    render(): React.ReactNode {
        const { children } = this.props;
        const { error } = this.state;

        if (error)
            return (
                <ErrorMessage
                    variant="full-page"
                    illustration="fatalError"
                    title={formatMessage('errors.default')}
                    className="w-auto"
                />
            );

        return children;
    }
}

const withErrorBoundary =
    <P extends object>(Component: React.ComponentType<P>) =>
    (props: P) =>
        (
            <ErrorBoundary>
                <Component {...props} />
            </ErrorBoundary>
        );

export default withErrorBoundary;
