import React, {Component} from 'react'
import {TouchableOpacity, View, Alert} from 'react-native'
import Image from 'react-native-fast-image'
import {NavigationEvents} from 'react-navigation'
import {Badge, Button} from 'native-base'
import Icon from 'src/components/Icon'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import {BackgroundImage} from '../../components/BackgroundImage'
import Text from '../../components/Text';
import LinearGradient from 'react-native-linear-gradient';
import {bindActionCreators} from 'redux'
import {appCleanToken, appCleanUser, appCleanProjectID} from '../../redux/app/action'
import {connect} from 'react-redux'
import {clearToken} from "../../api/api";
import DeviceInfo from 'react-native-device-info';
import { t } from 'src/utils/i18n'
import {getUserProfile, logout} from "../../api/UserApi";
import IndicatorLoading from '../../components/IndicatorLoading'
import IconEvil from 'react-native-vector-icons/EvilIcons'

const buildVersion = DeviceInfo.getVersion()
const buildNumber = DeviceInfo.getBuildNumber()

function ButtonBar({
                     title, iconName, iconFamily, callback = () => {
  }
                   }) {
  return <TouchableOpacity style={{borderBottomColor: 'rgba(0,0,0,0.25)', borderBottomWidth: 1, backgroundColor: 'white'}}
                           onPress={callback}>
    <View style={styles.list_item}>
      {
        iconFamily === 'IconEvil' ?
          <View style={{width: 29, alignItems: 'center', marginLeft: -3}}>
            <IconEvil name={iconName} size={32} style={{fontWeight: '500'}} color="#269A21"/>
          </View> :
          <View style={{width: 25, alignItems: 'center'}}>
            <Icon name={iconName} size={20} color="#269A21"/>
          </View>
      }
      <Text style={styles.textTitleService}>{title}</Text>
      <Icon name='ic_back' size={16} color="#269A21" style={{transform: [{rotate: '180deg'}]}}/>
    </View>
  </TouchableOpacity>
}

class ServiceScreen extends Component {
  constructor(props) {
    super(props)
    this._logout = this._logout.bind(this)
    this.state = {
      auth: false,
      fb_is_link: false,
      user: {
        point: 0
      },
      profileImage : require('../../../assets/images/praw.png'),
      isLoadingLogout: false
    }
  }

  componentDidMount() {
    this.initData()
  }

  initData() {
    if (this.props.token != null && this.props.user != null) {
      this.setState({
        user: this.props.user,
        auth: true
      },() => {
        // console.log('USER SHOW > ',this.props.user)
      })
    } else {
      this.setState({
        auth: false
      })
    }
  }

  _logout() {
    this.setState({
       isLoadingLogout : true
    }, () => {
      logout()
      .then(res => {
        console.log('response >>> ', res.data);
        if(res.status && res.status === 200){
          clearToken();

          setTimeout(() => {
            this.props.appCleanUser();
            this.props.appCleanToken();
            this.props.appCleanProjectID();
            this.setState({
              auth: false
            }, () => {
              this.setState({ isLoadingLogout: false})
              this.props.navigation.navigate('HomeScreen',{isLogin:true})
            })
          }, 500)
        }else {
          this.setState({ isLoadingLogout: false})
          Alert.alert('Logout unsuccessfully');
        }
      })
    })
  }

  getUserData(){
    if (this.props.token != null && this.props.user != null) {
      getUserProfile()
        .then(res => {
          console.log('res.ok >>>> ', res.ok)
          if(res.ok){
            let image = require('../../../assets/images/praw.png')
            let fb_link = false;

            if (res.data.user){
              if(res.data.user.image && res.data.user.image.url) {
                image = {
                  uri: res.data.user.image.url
                }
              }

              if(res.data.user && res.data.user.fb_is_link) {
                fb_link = res.data.user.fb_is_link
              }
            }

            
            console.log('Service: getUserData:')
            console.log('Service: ---- >',res.data)
            this.setState({
              user: {
                ...res.data.user,
                point: res.data.point_balance
              },
              profileImage: image,
              auth: true,
              fb_is_link: fb_link
            })
          }
        })
    } else {
      this.setState({
        auth: false
      })
    }
  }

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <NavigationEvents
          onDidFocus={() => {
            // this.initData()
            console.log('onDidfocus')
            this.getUserData()
          }}
        />
        <BackgroundImage>
          <View style={styles.container}>
            {this.state.auth == true ?
              <View style={[styles.profile, {borderBottomColor: '#00000040', borderBottomWidth: 1}]}>
                <View style={styles.profile_image}>
                  <Image source={this.state.profileImage} style={{height: 64, width: 64, flex: 1,borderRadius: 50}} resizeMode={'contain'}/>
                </View>
                <View style={styles.profile_detail}>
                  <View style={{flexDirection:'row',alignItems:'center'}}>
                    <Text style={{fontSize: 14}} numberOfLines={1} ellipsizeMode={'tail'}>
                      {
                        this.state.auth == true && this.state.user != null && this.state.user != ""
                          ? this.state.user.name
                          : null
                      }
                    </Text>
                    {
                      (this.state.fb_is_link !== false) &&
                      <Image source={require('../../../assets/images/icon_fb.png')} style={{height:25,width:25, marginLeft:15}}/>

                    }
                  </View>
                  <Badge style={{backgroundColor: '#269A21', borderRadius: 50, marginLeft: 5, height: 24, marginTop: 5, justifyContent: 'center'}}>
                    <Text style={{fontSize: 14, color: 'white', marginHorizontal: 10}}><Icon name="ic_star" size={14} color="white"/> {this.state.user && this.state.user.point ? this.state.user.point : 0}</Text>
                  </Badge>
                </View>
                <TouchableOpacity
                  style={{flex: 1, justifyContent: 'center', width: 45,}}
                  onPress={() => this.props.navigation.navigate('Profile', {
                    user: this.props.user
                  })}>
                  <Icon name="ic_back" size={24} color="rgba(0, 0, 0, 0.25)" style={{
                    transform: [{rotate: '180deg'}]
                  }}/>
                </TouchableOpacity>
              </View> : null}
            <View style={[styles.services]}>
              {
                this.props.token != null &&
                <ButtonBar title={t('request_repair_other')} iconName='icon_repair' callback={() => this.props.navigation.navigate('Repair')}/>
              }
               {
                this.props.token != null &&
                <ButtonBar title={t('mail_and_parcel')} iconName='ic_newspaper' callback={() => this.props.navigation.navigate('Object',{
                  user:this.props.user
                })}/>
              }
              {
                this.props.token != null &&
                <ButtonBar title={t('notification')} iconName='ic_bell' callback={() => this.props.navigation.navigate('SettingsNotification')}/>
              }
              {
                this.props.token != null &&
                <ButtonBar title={t('move_out')} iconName='archive' iconFamily={'IconEvil'} callback={() => this.props.navigation.navigate('MoveOut')}/>
              }
              {
                this.props.token != null &&
                <ButtonBar title={t('faqs')} iconName='ic_qa' callback={() => this.props.navigation.navigate('Question')}/>
              }
              <ButtonBar title={t('suggestion')} iconName='ic_question_circle' callback={() => this.props.navigation.navigate('Suggestion')}/>
              {this.state.auth == true ? <TouchableOpacity
                onPress={() => {
                  Alert.alert(
                    t('logout'),
                    t('logout_confirm'),
                    [
                      {text: t('cancel'), style: 'cancel'},
                      {text: t('ok'), onPress: () => this._logout()},
                    ],
                    {cancelable: false}
                  )
                }}
              >
                <View style={styles.list_item}>
                  <Icon name="ic_power_off" size={20} color="#269A21"/>
                  <View style={{marginLeft: 20}}>
                    <Text style={{fontSize: 14, color: '#00420A'}}>{t('logout')}</Text>
                  </View>
                </View>
              </TouchableOpacity> : null}
            </View>
            <View style={{flex:1,justifyContent:'flex-end',paddingRight:5}}>
              <Text style={{textAlign:'right',color:'#00000026',fontSize:12}}>v{buildVersion} ({buildNumber})</Text>
            </View>
          </View>

          <IndicatorLoading loadingVisible={this.state.isLoadingLogout}/>
        </BackgroundImage>
      </LinearGradient>
    )
  }
}

const styles = {
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  profile: {
    padding: 16,
    height: 96,
    flexL: 1,
    flexDirection: 'row',
    backgroundColor: '#fff',
  },
  profile_image: {
    height: 64,
    width: 64,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 32,
    borderColor: 'black'
  }
  ,
  profile_detail: {
    flex: 1,
    marginLeft: 5,
    justifyContent: 'center',
  },
  services: {
    height: '80%',
  },
  list_item: {
    height: 55,
    flexDirection: 'row',
    backgroundColor: '#fff',
    paddingHorizontal: 16,
    alignItems: 'center'
  },
  textTitleService: {
    flex: 1,
    paddingLeft: 16,
    fontSize: 14,
    color: '#00420A'
  }
}
const mapDisPatchToProps = state => {
  return state.app
}
const Logout = dispatch => bindActionCreators({appCleanToken, appCleanUser, appCleanProjectID}, dispatch)
export default connect(mapDisPatchToProps, Logout)(ServiceScreen)
