import { Button, Dialog, Portal, RadioButton} from 'react-native-paper';
import React, { useEffect, useState } from 'react';
import {
  Alert,
  Text,
  TextInput,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  cancelCallForward,
  forwardCallsToPhoneNumber,
  forwardCallToPersonalMobile,
  forwardToPersonalPhone,
  redirectCallsToVoiceMail,
} from '../../store/pbx/pbxSlice';
import { ForwardCallStatus } from '../../store/pbx/types';
import { Logger } from '../../utils/Log';
import { IStyledProps } from '../common/types';
import Icon from 'react-native-vector-icons/Ionicons'
import { useAppDispatch, useAppSelector } from '../../store/hooks';

const logger = new Logger('ForwardCalls');
interface IProps
  extends IStyledProps<IForwardCallsViewStyleProps> { }

interface IForwardCallsViewStyleProps {
  telephonyOptionsView?: ViewStyle;
  telephonyOptionsHeader?: ViewStyle;
  descriptionText?: TextStyle;
  headerText?: TextStyle;
  phoneNumberInput?: TextStyle;
  confirmedText?: TextStyle;
  forwardTitle?: TextStyle;
  radioItem?:ViewStyle;
  radioText?:TextStyle;
}
/**
 *
 * @module
 * @name Telephony
 */
export const ForwardCalls: React.FunctionComponent<IProps> = ({
  style,
}) => {
  const mergedStyle = { ...defaultStyle, ...style };
  const dispatch = useAppDispatch();
  const forwardStatus =  useAppSelector((state) => state.pbx.forwardStatus);
  const forwardNumberDestination =  useAppSelector((state) => state.pbx.forwardPhoneNumber);
  const forwardOptions =  useAppSelector((state) => state.pbx.forwardOptions);
  const forwardCallStatus = forwardStatus as keyof typeof ForwardCallStatus;
  const [selectedForwardStatus, setSelectedForwardStatus] = useState<string>(
    forwardCallStatus
  );
  const [forwardDialogVisible, setForwardDialogVisible] = useState(false);
  const [phoneDialogVisible, setPhoneDialogVisible] = useState(false);
  const [phoneNumber, setPhoneNumber] = useState<string>('');
  useEffect(() => {
    eventEmitter.addListener(
      EventType.CallForwardingResult,
      (callForwardResult: string) => {
        onCallForwardResult(callForwardResult);
      }
    );
  }, []);
  const onCallForwardResult = (result: string) => {
    if (result != null) {
      setSelectedForwardStatus(selectedForwardStatus);
      Alert.alert(Strings.telephonyForwardTitle, Strings.telephonyForwardError);
    }
  };
  const onForwardStatusSelected = (status: string) => () => {
    logger.info(`onForwardStatusSelected: ${status}`);
    if (status === ForwardCallStatus.telephonyForwardVoicemail) {
      logger.info(`onForwardStatusSelected: redirect Calls to VoiceMail`);
      dispatch(redirectCallsToVoiceMail());
    } else if (status === ForwardCallStatus.telephonyForwardOtherNumber) {
      logger.info(`onForwardStatusSelected: redirect Calls to phone Number`);
       openPhoneNumberDialog()
    } else if (status === ForwardCallStatus.telephonyCancelForward) {
      logger.info(`onForwardStatusSelected: cancel Call Forwarding`);
      dispatch(cancelCallForward());
    } else if (status === ForwardCallStatus.telephonyForwardPersonalMobile) {
      logger.info(`onForwardStatusSelected: redirect Calls to personal mobile`);
      dispatch(forwardCallToPersonalMobile());
    } else if (status === ForwardCallStatus.telephonyForwardPersonalPhone) {
      logger.info(`onForwardStatusSelected: redirect Calls to personal phone`);
      dispatch(forwardToPersonalPhone());
    }
    setSelectedForwardStatus(status);
    openForwardOptionsDialog();
  };
  const onPhoneNumberChanges = (text: string) => {
    setPhoneNumber(text);
  };
  const openForwardOptionsDialog = () => {
    setForwardDialogVisible(!forwardDialogVisible);
  };
  const openPhoneNumberDialog = () => {
    setPhoneDialogVisible(!phoneDialogVisible);
  };

  const confirmPhoneNumber = () => {
    forwardCallsToPhoneNumber(phoneNumber);
    openPhoneNumberDialog();
  };
  return (
    <View
      style={{
        marginTop: 10,
        marginBottom: 10,
      }}
    >
      <Text style={mergedStyle.forwardTitle}>
        {Strings.telephonyForwardTitle}
      </Text>
      <TouchableOpacity
        style={mergedStyle.telephonyOptionsHeader}
        onPress={openForwardOptionsDialog}
      >
        {forwardCallStatus === ForwardCallStatus.telephonyForwardOtherNumber ? (
          <Text style={mergedStyle.headerText}>
            {Strings.formatString(
              Strings.telephonyForwardNumberValue,
              forwardNumberDestination
            )}
          </Text>
        ) : (
          <Text style={mergedStyle.headerText}>
            {Strings.ForwardCallStatus[forwardCallStatus]}
          </Text>
        )}
        <Icon name="arrow-forward" />
      </TouchableOpacity>
      <Text style={mergedStyle.descriptionText}>
        {Strings.telephonyForwardDescription}{' '}
      </Text>
      <Portal>
      {/* Forward Options Dialog */}
      <Dialog visible={forwardDialogVisible} onDismiss={openForwardOptionsDialog}>
        <Dialog.Title>{Strings.telephonyForwardTitle}</Dialog.Title>
        <Dialog.Content>
          <View style={{ width: 300 }}>
            {forwardOptions.map((option) => (
              <RadioButton.Group
                key={option}
                onValueChange={onForwardStatusSelected} // Update the function signature
                value={option}
              >
                <View style={mergedStyle.radioItem}>
                  <RadioButton value={option} />
                  <Text style={mergedStyle.radioText}>
                    {Strings.ForwardCallStatus[option as keyof typeof ForwardCallStatus]}
                  </Text>
                </View>
              </RadioButton.Group>
            ))}
          </View>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onPress={openForwardOptionsDialog}>{Strings.cancel}</Button>
        </Dialog.Actions>
      </Dialog>

      {/* Phone Number Dialog */}
      <Dialog visible={phoneDialogVisible} onDismiss={openPhoneNumberDialog}>
        <Dialog.Title>{Strings.telephonyForwardNumber}</Dialog.Title>
        <Dialog.Content>
          <View style={{ width: 300 }}>
            <TextInput
              style={mergedStyle.phoneNumberInput}
              value={phoneNumber}
              onChangeText={onPhoneNumberChanges}
            />
          </View>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onPress={confirmPhoneNumber}>{Strings.ok}</Button>
        </Dialog.Actions>
      </Dialog>
    </Portal>
    </View>
  );
};
const defaultStyle: IForwardCallsViewStyleProps = {
  telephonyOptionsHeader: {
    flexDirection: 'row',
    backgroundColor: 'white',
    marginTop: 10,
    marginBottom: 10,
    borderColor: '#dedde1',
    borderWidth: 1,
    minHeight: 44,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  descriptionText: {
    color: '#adadad',
    fontSize: 13,
    paddingLeft: 10,
    paddingRight: 10,
    fontFamily: 'System',
  },
  headerText: {
    fontFamily: 'System',
    maxWidth: 220,
    fontSize: 15,
  },
  phoneNumberInput: {
    height: 40,
    borderBottomColor: '#0086CF',
    borderBottomWidth: 1,
  },
  confirmedText: {
    color: '#0086CF',
    marginTop: 10,
    fontSize: 18,
    fontWeight: 'bold',
  },
  forwardTitle: {
    color: 'gray',
    fontSize: 15,
    paddingLeft: 10,
    fontFamily: 'System',
  },
  radioItem: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 5,
  },
  radioText: {
    marginLeft: 10,
  },
};
