import React, { Component } from 'react'
import { TouchableOpacity, View, Alert, ScrollView, SafeAreaView, KeyboardAvoidingView, Platform } from 'react-native'
import Image from 'react-native-fast-image'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import { CustomButton } from '../../components/CustomButton'
import { CustomInput } from '../../components/CustomInput'
import { login } from '../../api/UserApi'
import { setToken } from '../../api/api'
import { BackgroundImage } from '../../components/BackgroundImage'
import LinearGradient from 'react-native-linear-gradient'
import Text from '../../components/Text'
import { bindActionCreators } from 'redux'
import { appSetDevice, appSetPushToken, appSetToken, appSetUser } from '../../redux/app/action'
import {connect} from 'react-redux'
import IndicatorLoading from '../../components/IndicatorLoading';
import { locale, t } from '../../utils/i18n'


class LoginScreen extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      username: null,
      password: null,
    }
    this._login = this._login.bind(this)
  }

  _login() {
    if (this.state.username && this.state.password) {

      var regex = /^\d+$/;

      if (regex.test(this.state.username) === true) {
        let params = {
          mobile: this.state.username,
          password: this.state.password
        }
        this.setState({isLoading:true})
        login(params)
        .then((res) => {
          if (res.ok) {
            if (res.data.token) {
              setToken(res.data.token)
              this.props.appSetToken(res.data.token)
              this.props.appSetUser(res.data.user)
              setTimeout(() => {
                this.setState({isLoading:false},() => {
                  this.props.navigation.navigate('HomeScreen',{isLogin:true})
                })
              }, 300);
            }
          } else {
            setTimeout(() => {
              Alert.alert(null, 'ท่านกรอก บัญชีผู้ใช้งาน หรือ รหัสผ่านผิด')
            }, 600);
          }
          this.setState({isLoading:false})
        })
      } else {
        Alert.alert(null, 'ท่านกรอกรูปแบบโทรศัพท์ไม่ถูกต้อง')
      }
    } else {
      Alert.alert(null, 'กรุณากรอกข้อมูลให้ครบถ้วน')
    }
  }

  render() {
    return (
      <SafeAreaView style={{flex: 1}}>
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
        <KeyboardAvoidingView style={{flex:1}} keyboardVerticalOffset={Platform.OS == 'ios' ? 70 : 0} behavior={Platform.OS == 'ios' ? "padding" : ""} enabled>
          <ScrollView showsVerticalScrollIndicator={true} style={{ flex: 1}}>
            <View style={styles.container}>

              <View style={styles.logo}>
                {/*<Text> Logo </Text>*/}
                <View style={{
                  flexGrow: 1, alignItems: 'center', justifyContent: 'center', paddingVertical: 10,
                }}>
                  <Image
                    style={{ width: 170, height: 170 }}
                    source={require('../../../assets/images/logo_white_border.png')}
                  />
                  <View style={{ marginTop: 5, alignItems: 'center', }}>
                    <Text style={{ fontSize: 28, color: '#FFF', fontFamily: 'Prompt-Medium' }}>เจริญสินธานี</Text>
                    <Text style={{ fontSize: 18, color: '#FFF' }}>({t('room_for_rent')})</Text>
                  </View>
                </View>
              </View>
              <View style={styles.form}>
                <View style={styles.row}>
                  <CustomInput
                    maxLength={10}
                    keyboardType="numeric"
                    onChangeText={(e) => {
                      this.setState({
                        username: e
                      })
                    }}
                    onEndEditing={(e) => {
                      this.setState({
                        username: e.nativeEvent.text
                      })
                    }}
                    inputTextAlign={'left'}
                    iconName={'ic_user'}
                    placeholder={t('phone')}
                    placeholderTextColor={'#FFFFFF40'}
                    style={styles.form_input} />
                </View>
                <View style={styles.row}>
                  <CustomInput

                    inputTextAlign={'left'}
                    secureTextEntry={true}
                    iconName={'ic_key'}
                    placeholder={t('password')}
                    placeholderTextColor={'#FFFFFF40'}
                    onChangeText={(e) => {
                      this.setState({
                        password: e
                      })
                    }}
                    onEndEditing={(e) => {
                      this.setState({
                        password: e.nativeEvent.text
                      })
                    }}
                    style={styles.form_input} />
                </View>
                <View style={[styles.row, { marginTop: 15 }]}>
                  <CustomButton
                    colorText={'#2470A1'}
                    weightText={'Prompt-Bold'}
                    title={t('login')}

                    sizeText={16}
                    style={[styles.btn_login]}
                    onPress={this._login}
                  //onPress={() => { this.props.navigation.navigate('HomeScreen') }}
                  />
                </View>
                <View style={{marginTop:10}}>
                  <View style={[styles.row, { flex: 1, flexDirection: locale() == 'my' ? 'column' : 'row', alignItems: 'center', textAlign: 'center', justifyContent: 'center' }]}>
                    <Text style={{ color: '#FFF', fontSize: 15,/* fontFamily: 'Prompt-Regular', */ }}> {t('not_a_member')}  </Text>
                    <TouchableOpacity onPress={() => { this.props.navigation.navigate('Register') }}>
                      <Text style={{ color: '#FFF', fontSize: 15, fontFamily: 'Prompt-Bold' }}> {t('create_account')} </Text>
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
            </View>
          </ScrollView>
          </KeyboardAvoidingView>
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
      </SafeAreaView>
    )
  }
}

//export default LoginScreen
const mapDisPatchToProps = state => {
  return state.app
}
const setUser = dispatch => bindActionCreators({ appSetToken, appSetPushToken, appSetDevice, appSetUser }, dispatch)
export default connect(mapDisPatchToProps, setUser)(LoginScreen)

const styles = {
  container: {
    flex: 1,
    //backgroundColor: 'rgba(53, 151, 12,0.8)'||'#359234',

    // flexGrow: 1,
    // flexDirection: 'column',
    // height: GetWidthHeightDevice.HeightContainer

  },
  logo: {
    // flex: 2,
    // height: '50%',
    // flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    //backgroundColor: "rgba(53, 151, 12,0.3)"||'#359234',

  },
  form: {
    // height: '45%',
    flex: 1,
    padding: 30,
    paddingBottom: 0,
    // backgroundColor: 'red',
  },
  row: {
    // flex: 1,
    flexDirection: 'row',
    marginBottom: 5,
  },
  form_address: {
    // flex: 2,
    padding: 10,
    paddingBottom: 0,
    // backgroundColor:"green",
  },
  step_indicator: {
    // flex: 1,
  },
  buttons: {
    paddingLeft: 15,
    paddingRight: 15,
    flexGrow: 1,
    // padding: 10,
    // backgroundColor: 'red',
    // alignItems: 'center',
    // justifyContent: 'center',
    position: 'absolute',
    flexDirection: 'row',
    marginHorizontal: 15,
    bottom: 15,
    left: 25
  },
  row_grow: {
    flexGrow: 1,
    // marginLeft: 5
    // backgroundColor:"red",
  },
  row_grow_first: {
    flexGrow: 1,
    marginRight: 5,
    // backgroundColor:"blue",
  },
  headerTitle: {
    color: '#DA7A16',
    marginVertical: 5

  },
  form_input: {
    backgroundColor: 'rgba(0,0,0,0)',
    borderColor: 'white', borderRadius: 30,
    borderWidth: 1,
  },
  btn_login: {
    backgroundColor: 'white',
    borderRadius: 30, width: '100%',

  }, btn_login_fb: {
    marginLeft: 10,
    backgroundColor: '#3b5998',
    borderRadius: 30, width: '20%',

  }

}
