import React, { useEffect, useState } from 'react';
import { View, Text } from 'react-native';
import { useConnection } from 'src/contexts/ConnectionContext';
import { styles } from './styles';
import { initializeBanner, showBanner } from 'src/utils/bannerUtils';
import { openDatabases } from 'src/db';

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

  useEffect(() => {
    initializeBanner(setVisible, setBannerMessage);

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

  if (!visible) return null;

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

export default ConnectionBanner;
