import type { FC } from 'react';
import React from 'react';
import { ErrorMessage } from '../errorMessage';

interface State {
    error?: Error;
}

interface Props {
    children?: React.ReactNode;
    path?: string | string[];
    showDetails?: boolean | undefined;
    errorComponent?: FC<{ error: Error }>;
    onError?: (error: Error, info: React.ErrorInfo) => void;
}

export class ErrorBoundary extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.state = {};
    }

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

    componentDidCatch(error: Error, info: React.ErrorInfo) {
        this.props.onError?.(error, info);
        this.setState({ error });
    }

    render() {
        const { error } = this.state;
        const { children, showDetails, errorComponent: ErrorComponent } = this.props;

        if (!error) return children;

        if (ErrorComponent) return <ErrorComponent error={error} />;

        return <ErrorMessage error={showDetails ? error : undefined} />;
    }
}
