import React, { FunctionComponent, useEffect, useState } from 'react';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  getVoiceMailCounter,
  updateMissedCounter,
  updateVoiceMailsCounter,
} from '../../store/callLogs/callLogSlice';
import { Logger } from '../../utils/Log';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { Text, View } from 'react-native';


 export const EventsTabIcon: FunctionComponent = () => {
  const logger = new Logger('EventsTabIcon');
  const [missedCallsCounter, setMissedCallsCounter] = useState<number>(0);
  const dispatch = useAppDispatch();
  const missedCounter = useAppSelector((state) => state.callLogs.missedCounter);
  useEffect(() => {
    getVoiceMailCounter();
    eventEmitter.addListener(
      EventType.MissedCallUnreadCounterUpdated,
      (counter: number) => {
        logger.info(`MissedCallsCounterUpdated: ${counter}`);
        setMissedCallsCounter(counter);
        dispatch(updateMissedCounter(counter))
      }
    );
    eventEmitter.addListener(
      EventType.VoiceMailUnreadCounterUpdated,
      (counter: number) => {
        logger.info(`VoiceMailsCounterUpdated: ${counter}`);
        dispatch(updateVoiceMailsCounter(counter));
      }
    );
  }, []);
  if (missedCounter > 0) {
    return (
      <View
        style={{
          width: 16,
          height: 16,
          backgroundColor: 'red',
          borderRadius: 8,
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 2,
          marginLeft: 5,
        }}
      >
        <Text style={{ color: 'white', fontSize: 10, fontWeight: 'bold' }}>
          {missedCounter}
        </Text>
      </View>
    );
  } else return null;
};
