
import React, { FunctionComponent, useEffect } from 'react';
import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  getCallLogs,
  getCallLogsResult,
  getMissedCall,
  getMissedCallResult,
  getVoiceMailCapabilities,
  getVoiceMailCapabilitiesResult,
  markMissedCallsAsRead,
  updateCallLogsPresence,
} from '../../store/callLogs/callLogSlice';
import { ICallLog } from '../../store/callLogs/types';
import { Presence } from '../../store/contacts/types';
import { forwardCallToVoiceMail } from '../../store/pbx/pbxSlice';

import { Logger } from '../../utils/Log';
import { CallLogsView } from './CallLogsView';
import { VoiceMailsView } from './VoiceMailsView';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { Text, Button, Surface, useTheme, Badge } from 'react-native-paper';
import { StyleSheet, View } from 'react-native';


interface ICallLogsProps {
  onClickCallLogAction?: (callLog: ICallLog) => void;
}

/**
 * @module
 * @name CallLogs
 * @version SDKVERSION
 * @public
 * @description
 *
 * This module for managing Call history for the Webrtc and PBX and you can use it for showing the 'all call history','missed calls' and 'voice messages'
 *
 */

const CallLogsContainer: FunctionComponent<ICallLogsProps> = ({onClickCallLogAction}) => {
  const logger = new Logger('CallLogsContainer');
  const theme = useTheme();
  const [selectedTab, setSelectedTab] = React.useState<number>(1);
  const dispatch = useAppDispatch();
  const callLogs = useAppSelector((state) => state.callLogs.callLogs);
  const missedCallLogs = useAppSelector((state) => state.callLogs.missedCallLogs);
  const loading = useAppSelector((state) => state.callLogs.loading);
  const isVoiceMailAllowed = useAppSelector((state) => state.callLogs.isVoiceMailAllowed);
  const voiceMailNumber = useAppSelector((state) => state.callLogs.voiceMailNumber);
  const voiceMailCounter = useAppSelector((state) => state.callLogs.voiceMailCounter);

  useEffect(() => {
    dispatch(getCallLogs());
    dispatch(getMissedCall());
   dispatch( getVoiceMailCapabilities());
    eventEmitter.addListener(
      EventType.CallLogsUpdated,
      (allCalls: ICallLog[]) => {
        dispatch(getCallLogsResult(allCalls))
      }
    );
    eventEmitter.addListener(
      EventType.MissedCallLogsUpdated,
      (missedCalls: ICallLog[]) => {
        dispatch(getMissedCallResult(missedCalls))
      }
    );
    eventEmitter.addListener(
      EventType.PresenceUpdated,
      (eventData: { presence: Presence; contactJId: string }) => {
        dispatch(updateCallLogsPresence(eventData))
      }
    );
    eventEmitter.addListener(
      EventType.VoiceMailCapabilityUpdate,
      (eventData: { isVoiceMailAllowed: boolean; voiceMailNumber: string }) => {
        dispatch(getVoiceMailCapabilitiesResult(eventData))
      }
    );
    return () => {
    };
  }, []);

  const onRefreshData = () => {
    if (selectedTab === 0) {
      logger.info(`refresh Call Logs in active Tab :${selectedTab}`);
      dispatch(getCallLogs());

    } else {
      logger.info(`refresh missed Call Logs in active Tab :${selectedTab}`);
      dispatch(getMissedCall());

    }
  };
  const onCallVoiceMail = () => {
    forwardCallToVoiceMail(voiceMailNumber);
  };

  const renderTab = () => {
    switch (selectedTab) {
      case 1:
        return <CallLogsView refreshData={onRefreshData} callLogs={callLogs} loading={loading} onClickCallLogAction={onClickCallLogAction} />
      case 2:
        return <CallLogsView refreshData={onRefreshData} callLogs={missedCallLogs} loading={loading} onClickCallLogAction={onClickCallLogAction} />
      case 3:
        return <VoiceMailsView voiceMailNumber={voiceMailNumber} voiceMailCounter={voiceMailCounter} callVoiceMail={onCallVoiceMail} />
      default:
        return null
    }
  }
  return (
    <>
       <Surface style={styles.container}>
      <View style={styles.tabRow}>
        <Button
          mode={selectedTab === 1 ? 'contained' : 'outlined'}
          onPress={() => setSelectedTab(1)}
          style={[styles.tabButton, selectedTab === 1 && styles.selectedTabButton]}
          color={selectedTab === 1 ? 'white' : '#0086CF'}
        >
          <Text style={[styles.buttonText, selectedTab !== 1 && styles.unselectedButtonText]}>
            {Strings.all}
          </Text>
        </Button>
        <Button
          mode={selectedTab === 2 ? 'contained' : 'outlined'}
          onPress={() => {
            setSelectedTab(2);
            dispatch(markMissedCallsAsRead());
          }}
          style={[styles.tabButton, selectedTab === 2 && styles.selectedTabButton]}
          color={selectedTab === 2 ? 'white' : '#0086CF'}
        >
          <Text style={[styles.buttonText, selectedTab !== 2 && styles.unselectedButtonText]}>
            {Strings.missed}
          </Text>
        </Button>
        {isVoiceMailAllowed && voiceMailCounter > 0 && (
          <>
            <Button
              mode={selectedTab === 3 ? 'contained' : 'outlined'}
              onPress={() => setSelectedTab(3)}
              style={[styles.tabButton, selectedTab === 3 && styles.selectedTabButton]}
              color={selectedTab === 3 ? 'white' : '#0086CF'}
            >
              <Text style={[styles.buttonText, selectedTab !== 3 && styles.unselectedButtonText]}>
                {Strings.voicemail}
              </Text>
            </Button>
            <Badge style={styles.badge}>{voiceMailCounter}</Badge>
          </>
        )}
      </View>
    </Surface>
            {renderTab()}
        </>
  );
};

export const CallLogs = CallLogsContainer;

const styles = StyleSheet.create({
  container: {
    width: 300,
    alignSelf: 'center',
    paddingVertical: 10,
    elevation: 6,
    borderRadius: 8,
    backgroundColor: 'white',
  },
  tabRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabButton: {
    flex: 1,
    marginHorizontal: 4,
    borderRadius: 20,
  },
  selectedTabButton: {
    backgroundColor: '#0086CF',
  },
  buttonText: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  unselectedButtonText: {
    color: '#0086CF',
  },
  badge: {
    position: 'absolute',
    right: 15,
    top: -5,
    backgroundColor: 'red',
    color: 'white',
    fontSize: 10,
    paddingHorizontal: 5,
  },
});