import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { useConnection } from 'src/contexts/ConnectionContext';
import { styles } from './styles';

const ConnectionBanner = () => {
  const netInfo = useConnection();
  const [visible, setVisible] = useState(false);
  const [bannerMessage, setBannerMessage] = useState('');
  const [hadConnection, setHadConnection] = useState(netInfo?.isInternetReachable);

  useEffect(() => {
    if (netInfo?.isInternetReachable !== null) {
      if (hadConnection === false && netInfo?.isInternetReachable) {
        setBannerMessage('Internet connection restored!');
        showBanner();
      } else if (netInfo?.isInternetReachable === false) {
        setBannerMessage('No internet connection!');
        showBanner();
      }
      setHadConnection(netInfo?.isInternetReachable);
    }
  }, [netInfo?.isInternetReachable]);

  const showBanner = () => {
    setVisible(true);
    setTimeout(() => {
      setVisible(false);
    }, 3000);
  };

  if (!visible) return null;

  return (
    <View style={styles.banner}>
      <Text style={styles.text}>{bannerMessage}</Text>
    </View>
  );
};

export default ConnectionBanner;
