import React, {FC, useState, useEffect} from 'react';
import {Modal} from 'react-native';
import NetInfo from '@react-native-community/netinfo';
import SuccessIcon from '@assets/svg/Success';
import ErrorIcon from '@assets/svg/Error';
import {
  Overlay,
  Wrapper,
  Description,
  ButtonWrapper,
  SubTitle,
  CloseButton,
  RetryButton,
} from '@styles/components/error-modal';

interface IProps {
  type?: 'success' | 'error';
  description: string | undefined;
  hideModal: () => void;
  visible?: boolean;
  retry: () => void;
}

const ErrorModal: FC<IProps> = ({
  type,
  description,
  visible,
  hideModal,
  retry,
}) => {
  const [tryAgain, setTryAgain] = useState<string | undefined>();
  const [count, setCount] = useState<number>(0);
  const [isOffline, setOfflineStatus] = useState(false);
  useEffect(() => {
    const removeNetInfoSubscription = NetInfo.addEventListener(state => {
      const offline = !(state.isConnected && state.isInternetReachable);
      setOfflineStatus(offline);
      setTryAgain(undefined);
      setCount(0);
    });

    return () => removeNetInfoSubscription();
  }, [isOffline]);

  const handleRetry = () => {
    if (count < 2) {
      setCount(count + 1);
    } else {
      setTryAgain('Try again after sometime');
      setCount(0);
    }
    retry();
  };

  return (
    <Modal
      animationType="fade"
      transparent={true}
      visible={visible}
      onRequestClose={hideModal}
      testID="errMdl">
      <Overlay onPress={hideModal} activeOpacity={1} />
      <Wrapper edges={['bottom']}>
        {type === 'success' ? <SuccessIcon /> : <ErrorIcon />}
        <Description>{description}</Description>
        {type !== 'success' && (
          <>
            {description?.includes('Network') && (
              <>
                <SubTitle>{tryAgain}</SubTitle>
                <ButtonWrapper>
                  <CloseButton
                    title="Close"
                    onPress={hideModal}
                    variant="text"
                  />
                  {!tryAgain && (
                    <RetryButton
                      title="Retry"
                      onPress={() => {
                        handleRetry();
                        hideModal();
                      }}
                    />
                  )}
                </ButtonWrapper>
              </>
            )}
          </>
        )}
      </Wrapper>
    </Modal>
  );
};

export default ErrorModal;
