import React, { useEffect, useState } from 'react';
import {
  Alert,
  Platform,
  Switch,
  Text,
  TextInput,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import {
  getNomadicNumber,
  setMyMobileNumber,
  switchNomadic,
  unregisterNomadicStatusChangeListener,
} from '../../store/pbx/pbxSlice';
import { Logger } from '../../utils/Log';
import { IStyledProps } from '../common/types';
import Icon from 'react-native-vector-icons/Ionicons'
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { Button, Dialog, Portal } from 'react-native-paper';

const logger = new Logger('NomadicCard');
interface INomadicViewProps extends IStyledProps<INomadicViewStyleProps> { }
interface INomadicViewStyleProps {
  container?: ViewStyle;
  telephonyOptionsView?: ViewStyle;
  telephonyOptionsHeader?: ViewStyle;
  descriptionText?: TextStyle;
  headerText?: TextStyle;
  nomadicText?: TextStyle;
  nomadicView?: ViewStyle;
  confirmedText?: TextStyle;
  nomadicNumInput?: TextStyle;
}

const NomadicCard: React.FunctionComponent<INomadicViewProps> = ({ style }) => {
  const mergedStyle = { ...defaultStyle, ...style };
  const dispatch = useAppDispatch();
  const isVoipEnabled = useAppSelector((state) => state.pbx.isVoipEnabled);
  const isNomadicEnabled = useAppSelector((state) => state.pbx.isNomadicEnabled);
  const myDeviceNumber = useAppSelector((state) => state.pbx.deviceNumber);
  const nomadicNumber = useAppSelector((state) => state.pbx.nomadicNumber);
  const isNomadicFeatureActivated = useAppSelector((state) => state.pbx.isNomadicFeatureActivated);

  const [nomadicNumDialogVisible, setNomadicNumDialogVisible] = useState(false);
  const [voipSwitchValue, setVoipSwitchValue] = useState(isVoipEnabled);
  const [nomadicSwitchValue, setNomadicSwitchValue] = useState(isNomadicEnabled);

  useEffect(() => {
    getNomadicNumber();
    eventEmitter.addListener(EventType.NoNomadicNumberEntered, () => {
      Alert.alert(Strings.telephonyForwardError, Strings.EmptyPhoneNumberMsg);
    });
    return () => {
      dispatch(unregisterNomadicStatusChangeListener());
    };
  }, [nomadicNumber]);
  const changeNomadic = (value: boolean) => {
    setNomadicSwitchValue(value);
    logger.info(`changeNomadic: setNomadicSwitchValue to :${value}`);
    dispatch(switchNomadic({ isNomadicEnabled: value, isVoipEnabled: voipSwitchValue, nomadicType: 'nomadic' }))
  };
  const changeVoip = (value: boolean) => {
    setVoipSwitchValue(value);
    logger.info(`changeNomadic: setVoipSwitchValue to :${value}`);
    dispatch(switchNomadic({ isNomadicEnabled: nomadicSwitchValue, isVoipEnabled: value, nomadicType: 'voip' }))

  };
  const onNomadicNumberChanges = (text: string) => {
    dispatch(setMyMobileNumber(text));
  };
  const openNomadicNumDialog = () => {
    if (
      nomadicNumber &&
      Platform.OS === 'android' &&
      nomadicNumber === myDeviceNumber
    ) {
      return;
    }
    setNomadicNumDialogVisible(!nomadicNumDialogVisible);
  };
  const confirmNomadicNumber = () => {
    dispatch(setMyMobileNumber(nomadicNumber));
    openNomadicNumDialog();
  };
  return isNomadicFeatureActivated ? (
    <View>
      <TouchableOpacity
        style={mergedStyle.telephonyOptionsHeader}
        onPress={openNomadicNumDialog}
      >
        <Text style={mergedStyle.headerText}>
          {Strings.TelephonyNomadicNumber}
        </Text>
        {nomadicNumber != null ? (
          <Text style={mergedStyle.nomadicText}>{nomadicNumber}</Text>
        ) : (
          <View style={mergedStyle.nomadicView}>
            <Text style={mergedStyle.nomadicText}>
              {Strings.NomadicNoMobileNumber}
            </Text>
            <Icon name="arrow-forward" />
          </View>
        )}
      </TouchableOpacity>

      <Text style={mergedStyle.descriptionText}>
        {Strings.TelephonyNomadicNumberDescription}{' '}
      </Text>

      <View style={mergedStyle.telephonyOptionsHeader}>
        <Text style={mergedStyle.headerText}>
          {Strings.TelephonyNomadicMobile}
        </Text>
        <Switch
          thumbColor="white"
          trackColor={{ true: '#3786c9', false: 'grey' }}
          value={isNomadicEnabled}
          onValueChange={changeNomadic}
        />
      </View>
      <Text style={mergedStyle.descriptionText}>
        {Strings.TelephonyNomadicDescription}{' '}
      </Text>

      <View style={mergedStyle.telephonyOptionsHeader}>
        <Text style={mergedStyle.headerText}>
          {Strings.TelephonyNomadicVoip}
        </Text>
        <Switch
          thumbColor="white"
          trackColor={{ true: '#3786c9', false: 'grey' }}
          value={isVoipEnabled}
          onValueChange={changeVoip}
        />
      </View>
      <Text style={mergedStyle.descriptionText}>
        {Strings.TelephonyVoipDescription}{' '}
      </Text>

      <Portal>
      <Dialog visible={nomadicNumDialogVisible} onDismiss={openNomadicNumDialog}>
        <Dialog.Title>{Strings.myNumber}</Dialog.Title>
        <Dialog.Content>
          <View style={{ width: 300 }}>
            <TextInput
              style={mergedStyle.nomadicNumInput}
              value={nomadicNumber}
              onChangeText={onNomadicNumberChanges}
            />
          </View>
        </Dialog.Content>
        <Dialog.Actions>
          <Button onPress={confirmNomadicNumber}>{Strings.ok}</Button>
        </Dialog.Actions>
      </Dialog>
    </Portal>
    </View>
  ) : null;
};
export const NomadicView = NomadicCard;

const defaultStyle: INomadicViewStyleProps = {
  container: {
    backgroundColor: '#efeff4',
    justifyContent: 'space-between',
  },
  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,
  },
  confirmedText: {
    color: '#0086CF',
    marginTop: 10,
    fontSize: 20,
    fontWeight: 'bold',
  },
  nomadicNumInput: {
    height: 40,
    borderBottomColor: '#0086CF',
    borderBottomWidth: 1,
  },
  nomadicText: {
    fontSize: 15,
    color: 'gray',
    margin: 10,
  },
  nomadicView: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
};
