import React, { Component } from 'react'
import { ScrollView, View, Alert } from 'react-native'
import Image from 'react-native-fast-image'
import { Button } from 'native-base'
import { BackgroundImage_RegisterForm } from '../../components/BackgroundImage_RegisterForm'
import Text from '../../components/Text';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'src/components/Icon'
import { CustomButton } from '../../components/CustomButton'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { getUserProfile, requestDeleteAccount } from '../../api/UserApi';
import moment from 'moment'
import { NavigationEvents } from 'react-navigation'
import IndicatorLoading from '../../components/IndicatorLoading';
import { loginWithFacebook,disconnectWithFacebook } from '../../components/FacebookUtils';
import { t } from '../../utils/i18n'

class ProfileScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: false,
      user:{},
      room:null,
      profileImage: require('../../../assets/images/profile.png')
    }
    this.getUserData = this.getUserData.bind(this)
  }

  componentDidMount(){
    // this.getUserData()
    this.setState({
      isLoading: true
    })
  };

  getUserData(){
    this.setState({
      isLoading: true
    })
    getUserProfile()
    .then(res => {
      // console.log('user profile -------> ',res);
      if(res.ok){
        let image = require('../../../assets/images/profile.png')
         if (res.data.user.image){
           image = {
             uri: res.data.user.image ? res.data.user.image.url ? res.data.user.image.url : res.data.user.image : ''
           }
         }
        this.props.user.show_birth_date = res.data.user.birth_date
        this.setState({
          isLoading: false,
          user: res.data.user,
          room: res.data.room && res.data.room.length > 0 ? res.data.room[0] : null,
          profileImage : image,
        })
      }else{
        this.setState({
          isLoading: false
        })
      }
    })
  }

  connectFBSuccess = () => {
    this.state.user.fb_is_link = 't';
    Alert.alert('Connect with Facebook Success', '', [
      {
        text: 'ok',
        onPress: () => {
          this.getUserData()
        }
      }
    ])
  };

  disConnectFBSuccess = () => {
    this.state.user.fb_is_link = 'f';
    this.state.user.fb_token = null;
    Alert.alert('Disconnect with Facebook Success', '', [
      {
        text: 'ok',
        onPress: () => {
          this.getUserData()
        }
      }
    ])
  };

  refreshPage() {
      window.location.reload(false);
  }

  confirmDeleteAccount = () => {
    Alert.alert(t('title_delete_ac'), t('body_delete_ac'), [
      {
        text: t('cancel')
      },
      {
        text: t('ok'),
        onPress: () => {
          this.deleteAccount()
        }
      }
    ])
  }

  deleteAccount = () => {
    this.setState({
      isLoading: true
    }, () => {
      requestDeleteAccount().then((res) => {
        if(res.data?.success) {
          Alert.alert(t('success'))
          this.setState({
            isLoading: false
          })
        }else {
          Alert.alert(t('unsuccessful'), t('contact_admin_for_delete_ac'))
          this.setState({
            isLoading: false
          })
        }
      }) 
    })
  }

  render() {
    return (
      <LinearGradient colors={['#00420A', '#00420A']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <NavigationEvents
            onDidFocus={() => {
              console.log('getUserData');
              this.getUserData()
            }}
          />
        <BackgroundImage_RegisterForm >
          <ScrollView contentContainerStyle={styles.contentContainer}>
            <View style={styles.container}>
              <View style={{
                flexGrow: 1, backgroundColor: '#3AA40C', alignItems: 'center', paddingVertical: 20,
              }}>
                <Image
                  style={{ width: 120, height: 120, borderRadius: 60, borderColor: 'white', borderWidth: 2 }}
                  source={this.state.profileImage}
                />
              </View>
              <View style={{ flex: 1, padding: 15, }}>
                <View style={{ height: 385 }}>
                  <View >
                    <Text style={{ color: '#8BC34A', marginBottom: 10 }}>{t('profile')}</Text>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('category')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.is_customer ? t('customer') : t('guest')}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('name')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.name}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('email')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.email ? this.state.email : '-'}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('phone2')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.mobile}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('citizen_id')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.tax_id}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('gender')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.gender == "male" || this.state.user.gender == "ชาย" ? t('male') : t('female')}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('birth_date')}</Text>
                      <Text style={styles.data_field_style}>{this.state.user.birth_date ? moment(this.state.user.birth_date, 'DD-MM-YYYY').add(543, 'years').format('DD MMM YYYY') : ''}</Text>
                    </View>
                  </View>
                  {
                    this.state.room != null &&
                    <View>
                    <Text style={{ color: '#8BC34A', marginBottom: 10, marginTop: 10 }}>{t('accom_info')}</Text>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('accommodation')}</Text>
                      <Text style={styles.data_field_style}>{this.state.room.project_name}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('zone')}</Text>
                      <Text style={styles.data_field_style}>{this.state.room.zone_name}</Text>
                    </View>
                    <View style={{ flexDirection: 'row' }}>
                      <Text style={styles.text_field_style}>{t('room2')}</Text>
                      <Text style={styles.data_field_style}>{this.state.room.number}</Text>
                    </View>
                  </View>
                  }
                </View>
              </View>
            </View>
          </ScrollView>

          {
            !this.state.user.fb_is_link?
            <View style={{ justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0)' }}>
              <Button block style={{ backgroundColor: '#145EB3', marginHorizontal: 15 }}
                onPress={() => {
                  setTimeout( () => {
                    loginWithFacebook(this.connectFBSuccess)
                  },1000);
                }} >
                <Text style={{ color: '#ffffff', fontSize: 14 }}>{t('connect_facebook')}</Text>
              </Button>
            </View>
            :
            <View style={{ justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0)' }}>
              <Button block style={{ backgroundColor: '#145EB3', marginHorizontal: 15 }}
                onPress={() => {
                  disconnectWithFacebook(this.disConnectFBSuccess);
                }}
                >
                <Text style={{ color: '#ffffff', fontSize: 14 }}>{t('disconnect_facebook')}</Text>
              </Button>
            </View>
          }

          <View style={{ justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0)' }}>
            <Button block style={{ backgroundColor: '#145EB3', margin:15 }}
              onPress={() => { this.props.navigation.navigate('EditProfile',{
                user:this.state.user,
                image:this.state.profileImage,
              }) }}>
              <Text style={{ color: '#ffffff', fontSize: 14 }}><Icon name={'ic_edit'} size={15}/>  {t('edit_profile')} </Text>
            </Button>
          </View>

          <View style={{ justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0)' }}>
            <Button block
                style={{margin: 15, borderWidth: 0, backgroundColor: 'transparent', borderWidth: 0, elevation: 0}}
                onPress={() => { this.confirmDeleteAccount() }}>
              <Text style={{ color: 'red', fontSize: 16 }}> {t('delete_account')} </Text>
            </Button>
          </View>
        </BackgroundImage_RegisterForm>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

const styles = {
  container: {
    flexDirection: 'column',
    height: '100%',
  },
  image_profile: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: '25%',
  },
  text_field_style: {
    color: 'white',
    width: '35%',
    marginBottom: 8,
    fontSize: 14,
  },
  data_field_style: {
    color: 'white',
    marginLeft: 5,
    fontSize: 14,
    width: '65%',
  }
}

const mapDisPatchToProps = state => {
  return state.app
}
const prop_set = dispatch => bindActionCreators({   }, dispatch)
export default connect(mapDisPatchToProps, prop_set)(ProfileScreen)
