import type { FC, ComponentType } from 'react';
import React, { useState } from 'react';
import { useRoute } from '@react-navigation/native';
import * as sentryService from '../services/sentry.service';
import ErrorScreen from '../screens/ErrorScreen';
import ErrorBoundary from '../components/Errors/ErrorBoundary';

const withErrorBoundary = <ComponentProps extends object>(
    Component: ComponentType<ComponentProps>
): FC<ComponentProps> => {
    const WithErrorBoundary: FC<ComponentProps> & { router?: any } = ({
        ...props
    }: ComponentProps) => {
        const route = useRoute();

        const [screenError, setScreenError] = useState<any>();

        const handleScreenError = (error: any): void => {
            setScreenError(error);
            sentryService.logException(
                `Tab Level Error Boundary for screen ${route?.name} 
                invoked with an error ${error}`
            );
        };

        if (screenError) {
            return (
                <ErrorScreen
                    title="error.tab.title"
                    message="error.tab.message"
                    isTabLevel
                />
            );
        }

        return (
            <ErrorBoundary onError={handleScreenError}>
                <Component {...props} />
            </ErrorBoundary>
        );
    };
    // @ts-ignore
    WithErrorBoundary.router = Component.router;
    return WithErrorBoundary;
};

export default withErrorBoundary;
