import React from 'react';
import { isUserAuthenticated } from '@adminide-stack/user-auth0-client';
import { useNavigation } from '@react-navigation/native';
import { useSelector } from 'react-redux';
import DefaultAuthComponent from './UnAuthenticatedComponent';
import {
    withLifeCycleManaged,
    withInteractionsManaged,
    withLifeCycleInteractionsManaged,
} from './with-interactions-lifecycle-managed';

export const AuthWrapper = ({
    auth = false,
    component,
    unauthenticatedComponent = null,
    withLifeCycle = null,
    withInteraction = null,
    withLifeCycleInteraction = null,
    authority = null,
    extraPermissions = null,
}: any) => {
    const user = useSelector((state: any) => state.user);
    const { authenticated } = isUserAuthenticated();
    const navigation = useNavigation<any>();

    React.useEffect(() => {
        if (auth && !user?.profile) navigation.navigate('MainStack.Login');
    }, [auth, user]);

    const wrapperComponent = withLifeCycle
        ? withLifeCycleManaged(component, authority)
        : withInteraction
        ? withInteractionsManaged(component, withInteraction?.duration ?? null, authority)
        : withLifeCycleInteraction
        ? withLifeCycleInteractionsManaged(component, withLifeCycleInteraction?.duration ?? null, authority)
        : component;

    if (auth && !user?.profile) return unauthenticatedComponent ? unauthenticatedComponent : <DefaultAuthComponent />;
    else return wrapperComponent;
};

export default React.memo(AuthWrapper);
