import React from 'react';
import {
  View,
  Image,
  Text,
  TextInput,
  TouchableOpacity,
  BackHandler,
  Platform,
  StatusBar
} from 'react-native';
import {
  Container,
  Content,
  Header,
  Button,
  Toast,
  Loader
} from './../../../components';
import styles from './Styles/ChangePasswordStyle';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Images, Colors } from './../../../theme';
import Ionicons from 'react-native-vector-icons/Ionicons';
import i18n from './../../../i18n';
import { changePasswordRequest } from './../../../actions/UserAction';
import AsyncStorage from '@react-native-community/async-storage';
export interface Props {
  navigation: any;
  changePassword: any;
  loading: any;
}

interface State {
  oldPassword: any;
  newPassword: any;
  confirmPassword: any;
  showPassword: any;
  currentPassword: any;
}
class ChangePassword extends React.Component<Props, State> {
  changePasswordRefs: any = {};

  constructor(props: Props) {
    super(props);
    this.state = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
      showPassword: {},
      currentPassword: ''
    };
  }

  componentDidMount = () => {
    //this.getCreds();
    BackHandler.addEventListener('hardwareBackPress', this.backHandler);
  };

  componentWillUnmount = () => {
    BackHandler.removeEventListener('hardwareBackPress', this.backHandler);
  };

  getCreds = async () => {
    let creds = await AsyncStorage.getItem('creds');
    let credsObj:any={};
    if (creds) {
       credsObj = JSON.parse(creds);
      this.setState({ currentPassword: credsObj.password });
    }
    return credsObj.password
  };

  backHandler = () => {
    const { navigation } = this.props;
    return navigation.goBack();
  };

  moveFocus = (key: any) => {
    let toFocus = null;
    switch (key) {
      case 'oldPassword':
        toFocus = this.changePasswordRefs.newPassword.focus();
        break;
      case 'newPassword':
        toFocus = this.changePasswordRefs.confirmPassword.focus();
        break;
      default:
        toFocus = null;
    }
    return toFocus;
  };

  changePassword = async() => {
    let {
      oldPassword,
      newPassword,
      confirmPassword,
      currentPassword
    } = this.state;
    const { changePassword } = this.props;
    let creds = await AsyncStorage.getItem('creds');
    let credsObj:any={};
    if (creds) {
       credsObj = JSON.parse(creds);
      this.setState({ currentPassword: credsObj.password });
      currentPassword=credsObj.password 
    }
   if (oldPassword.length === 0) {
      Toast.errorBottom('Please enter your old password');
      return;
    }
    if (newPassword.length === 0) {
      Toast.errorBottom('Please enter new password');
      return;
    }
    if (confirmPassword.length === 0) {
      Toast.errorBottom('Please enter confirm new password');
      return;
    }
    if (newPassword.length <6) {
      Toast.errorBottom('Password should be at least 6 characters');
      return;
    }
    
    if (newPassword !== confirmPassword) {
      Toast.errorBottom('Password and confirm password does not match');
      return;
    }
    if (oldPassword !== currentPassword) {
      Toast.errorBottom('You have entered wrong old password');
      return;
    }
    let params = {
      current_password: currentPassword,
      password: newPassword,
      confirm_password: confirmPassword
    };
    changePassword(params);

  };

  renderInput = (key: any, value: any) => {
    let { showPassword } = this.state;
    return (
      <View style={styles.txtInputView}>
        <Text style={styles.labelTxt}>{i18n.t(`changePassword.${key}`)}</Text>
        <TextInput
          ref={(node: any) => {
            this.changePasswordRefs[key] = node;
          }}
          key={key}
          style={styles.txtInput}
          autoCapitalize={'none'}
          placeholder={'Enter ' + i18n.t(`changePassword.${key}`)}
          returnKeyType="next"
          secureTextEntry={key !== ' ' && !showPassword[key]}
          placeholderTextColor={Colors.borderGrey}
          value={value}
          onChangeText={val => {
            const obj: any = {};
            obj[key] = val;
            this.setState(obj);
          }}
          onSubmitEditing={() => {
            this.moveFocus(key);
          }}
        />

        <TouchableOpacity
          style={styles.eyeBtn}
          onPress={() => {
            showPassword[key] = !showPassword[key];
            this.setState({ showPassword });
          }}>
          <Ionicons
            name={showPassword[key] ? 'ios-eye-off' : 'ios-eye'}
            style={styles.eyeIcon}
          />
        </TouchableOpacity>
      </View>
    );
  };

  render() {
    const { oldPassword, newPassword, confirmPassword } = this.state;
    const { navigation, loading } = this.props;
    return (
      <>
        <Container
          transparentStatusBar
          safeAreaView={Platform.OS === 'ios' ? false : false}>
          <StatusBar barStyle="dark-content" backgroundColor="transparent" />
          <Content>
            <Header
              isTransparent
              hasHeaderThin
              hasBackBtn
              navigation={navigation}
            />
            {/* <Image style={styles.headerThin} source={Images.headerThin} /> */}
            <Image style={styles.keyLock} source={Images.keyLock} />
            <View style={styles.viewStyle}>
              <View style={styles.titleContainer}>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
                <Text style={styles.titleTxt}>Change Password</Text>
                <Image
                  style={styles.seperator}
                  source={Images.profileSeparator}
                />
              </View>

              {this.renderInput('oldPassword', oldPassword)}
              {this.renderInput('newPassword', newPassword)}
              {this.renderInput('confirmPassword', confirmPassword)}

              <Button
                hasShadow
                medium
                onPress={() => this.changePassword()}
                style={styles.shadowStyle}
                shadowRadius={15}
                buttonStyle={styles.changePasswordBtn}
                title={'Change Password'}
              />
            </View>
          </Content>
        </Container>
        <Loader show={loading} />
      </>
    );
  }
}

function mapStateToProps({ user }: any) {
  return {
    user: user.profile,
    loading: user.loading
  };
}

function mapDispatchToProps(dispatch: any) {
  return bindActionCreators(
    {
      changePassword: changePasswordRequest
    },
    dispatch
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ChangePassword);
