import React, { useEffect, useState } from 'react';
import {
  View,
  TouchableOpacity,
  Modal,
  ViewStyle,
  TextStyle,
  Text,
  TouchableWithoutFeedback
} from 'react-native';
import { Strings } from '../../resources/localization/Strings';
import { IStyledProps } from '../common/types';
import { Logger } from '../../utils/Log';
import { TextInput } from 'react-native-paper';
import { getHost, getHostResult, updateHost } from '../../store/configuration/appConfigSlice';
import { eventEmitter, EventType } from '../../services/EventEmitter';
import { useAppDispatch, useAppSelector } from '../../store/hooks';

const logger = new Logger('ApplicationInformation');

export interface IProps extends IStyledProps<IAppInfoStyleProps> {
  visible: boolean;
  closeModal: () => void;
  style?: IAppInfoStyleProps;
  onCancelPress?: () => void;
  onOkPress?: () => void;
  modalContent?: React.ReactNode;
  modalOptions?: React.ReactNode;
}
export interface IAppInfoStyleProps {
  modalBackground?: ViewStyle;
  modalContent?: ViewStyle;
  modalText?: TextStyle;
  modalOptions?: ViewStyle;
  modalOptionsText?: TextStyle
}
export const ApplicationInformation: React.FunctionComponent<IProps> = ({
  visible,
  closeModal,
  style,
  modalContent,
  modalOptions,
  onCancelPress,
  onOkPress
}) => {
  // Selectors
  const dispatch = useAppDispatch();
  const currentHost = useAppSelector((state) => state.appConfigReducer.host);
  const [host, setHost] = useState<string>('');
  const [isChangeHostEnable, setIsChangeHostEnable] = useState<boolean>(false);

  const modalMergedStyle = { ...defaultModalStyle, ...style };

  useEffect(() => {
    dispatch(getHost());
    eventEmitter.addListener(EventType.GetHostNameResult, (host: string) => {
      logger.info(`GetHostNameResult: ${host}`);
      dispatch(getHostResult(host));
      setHost(currentHost || '');
    })

    return () => {
      setHost('');
      setIsChangeHostEnable(false);
    };
  }, [visible]);


  const handleHostChange = (hostName: string) => {
    if (hostName.length > 0 && hostName !== currentHost) {
      setHost(hostName);
      setIsChangeHostEnable(true)
    } else {
      setIsChangeHostEnable(false)
    }
  };
  const onDefaultPress = () => {
    if (onCancelPress) {
      onCancelPress();
    } else {
      closeModal();
    }  };

  const onDefaultOkPress = async () => {
    closeModal();
    if (onOkPress) {
      onOkPress();
    } else if (isChangeHostEnable) {
    dispatch(updateHost(host))
    }
  };
  const renderModalContent = () => {
    if (modalContent) {
      return modalContent;
    } else {
      return (
        <>
          <Text style={modalMergedStyle.modalText}>{Strings.applicationInformation}</Text>
           <TextInput
            keyboardType="default"
            placeholder={Strings.host}
            placeholderTextColor="#0086CF"
            value={host}
            onChangeText={handleHostChange}
            mode="outlined"
            style={{ marginTop: 20 }}
          />
        </>
      )
    }
  }
  const renderModalOptions = () => {
    if (modalOptions) {
      return modalOptions;
    } else {
      return (
        <>
          <TouchableOpacity onPress={onDefaultPress}>
            <Text style={modalMergedStyle.modalOptionsText}>{Strings.cancel}</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={onDefaultOkPress}>
            <Text style={modalMergedStyle.modalOptionsText}>{Strings.ok}</Text>
          </TouchableOpacity></>
      )
    }
  }
  return (
    <Modal
    animationType="slide"
    transparent={true}
    visible={visible}
    onRequestClose={closeModal}
  >
    <TouchableWithoutFeedback onPress={closeModal}>
      <View style={defaultModalStyle.modalBackground}>
        <TouchableWithoutFeedback onPress={() => {}}>
          <View style={defaultModalStyle.modalContent}>
          {renderModalContent()}
          <View style={modalMergedStyle.modalOptions}>
          {renderModalOptions()}

          </View>
          </View>
        </TouchableWithoutFeedback>
      </View>
    </TouchableWithoutFeedback>
  </Modal>
);
};
const defaultModalStyle: IAppInfoStyleProps = {

  modalText: {
    textAlign: 'center',
    fontSize: 22,
    color: '#0086CF'
  },
  modalOptions: {
    flexDirection: 'row',
    marginTop: 40,
    alignSelf: 'flex-end'
  },
  modalOptionsText: {
    fontSize: 15,
    color: '#0086CF',
    marginRight: 10,
    marginLeft: 20
  },
  modalBackground: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    width: '80%',
    backgroundColor: 'white',
    borderRadius: 8,
    padding: 20,
  },
};