import React, { Component } from 'react'
import {
  View,
  ScrollView,
  TouchableOpacity,
  Platform,
  KeyboardAvoidingView,
  Alert
} from 'react-native'
import Image from 'react-native-fast-image'
import Icon from '../../components/Icon'
import { Picker } from 'native-base'
import { BackgroundImage_RegisterForm } from '../../components/BackgroundImage_RegisterForm'
import LinearGradient from 'react-native-linear-gradient'
import Text from '../../components/Text'
import { CustomInput } from '../../components/CustomInput'
import { CustomButton } from '../../components/CustomButton'
import { CustomPicker } from '../../components/CustomPicker'
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import { bindActionCreators } from 'redux'
import { appSetDevice, appSetUser, appCleanUser } from '../../redux/app/action'
import { connect } from 'react-redux'
import { edit_profile, project, getBuildingByProjectId } from '../../api/UserApi'
import moment from 'moment'
import ImagePicker from 'react-native-image-crop-picker'
import ActionSheet from 'react-native-action-sheet'
import CustomDatePicker from '../room/CustomDatePicker';
import { t } from '../../utils/i18n'

let ACTIONSHEET_BUTTONS = [
  t('take_photo'),
  t('from_gallery'),
  t('cancel')
]

// let DESTRUCTIVE_INDEX = 3;
let CANCEL_INDEX = 2

class EditProfileScreen extends Component {

  constructor (props) {
    super(props)
    this.edit_profile = this.edit_profile.bind(this)
    this.state = {
      user: {},
      image_url: require('../../../assets/images/profile.png'),
      project_list:[],
      building_list: [],
      selected_project: 0,
      project_name:t('choose_project'),
    }
    this.onImagePick = this.onImagePick.bind(this)
    this.onTakeCamera = this.onTakeCamera.bind(this)
  }

  componentDidMount () {
    const { navigation } = this.props
    const users_state = navigation.getParam('user', 'NO ITEM')
    const image = navigation.getParam('image', 'NO ITEM')
      console.log("defaultImage",image);
    if(image != null ){
        this.setState({
            image_url :image
        })
    }
    // console.log('check user state ----------- ',users_state)
    if(users_state.gender == null || users_state.gender == 'null'){
      console.log('NULL');
      // this.state.user.show_birth_date = users_state.birth_date;
      this.setState({
        user: {
          gender: 'male',
          name: users_state.name,
          ...users_state,
        }
      })
    }else{
      console.log('NOT NULL');
      this.setState({
        user: {
          ...users_state,
          name: users_state.name
        }
      })
    }

    // this.getProjectList()
  }

  getProjectList() {
    project()
      .then(res => {
        if (res.ok && res.data && res.data.data) {
          this.setState({
            project_list: res.data.data,
            selected_project: res.data.data[0].id
          })
        }
      })
  }

  getBuildingList() {
    getBuildingByProjectId(this.state.selected_project)
      .then(res => {
        if (res.ok) {
          this.setState({
            building_list: res.data.data
          })
        }
      })
  }

  edit_profile () {
    if(this.state.user.password != null || this.state.user.password != ''){
      if(this.state.user.password === this.state.user.confirm_password){
        edit_profile(this.state.user)
        .then(res => {
          if(res.ok){
            this.props.appSetUser(res.data)
            Alert.alert(t('save_success'), '', [{
              text: 'ok',
              onPress: () => {
                this.props.navigation.navigate('Profile')
              }
            }])              
          }else {
            Alert.alert(t('save_fail_and_try'), '', [{
              text: 'ok',
              onPress: () => {
                this.props.navigation.navigate('Profile')
              }
            }])
          }
        })
      }else{
        Alert.alert(t('incorrect_pw'), t('pw_not_match_and_retry'))
      }
    }else{
      edit_profile(this.state.user)
      .then(res => {
        if(res.ok){
          this.props.appSetUser(res.data)
          Alert.alert(t('save_success'), '', [{
            text: 'ok',
            onPress: () => {
              this.props.navigation.navigate('Profile')
            }
          }]) 
        }else {
          Alert.alert(t('save_fail_and_try'), '', [{
            text: 'ok',
            onPress: () => {
              this.props.navigation.navigate('Profile')
            }
          }])
        }
      })
    }
  }

  onImagePick () {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      includeBase64: true
    }).then(image => {
      console.log('received base64 image', image)
      let image_profile = {
        uri: image.path,
        type: image.mime,
        name: 'image_profile.jpg',
      }

      let image_data = { uri: `data:${image.mime};base64,` + image.data, width: image.width, height: image.height };
      this.setState({
        image_url: image_profile,
        images: null,
        user: {
          ...this.state.user,
          profile_image_id: image_profile,
          profile_image: image_data
        }
      })
    })
  }

  onTakeCamera () {
    ImagePicker.openCamera({
      cropping: true,
      width: 300,
      height: 300,
      includeExif: true,
      includeBase64: true
    }).then(image => {
      console.log('received image', image)
      let image_data = { uri: `data:${image.mime};base64,` + image.data, width: image.width, height: image.height };

      let image_profile = {
        uri: image.path,
        type: image.mime,
        name: 'image_profile.jpg',
      }
      this.setState({
        image_url: { uri: image.path, width: image.width, height: image.height, mime: image.mime },
        images: null,
        user: {
          ...this.state.user,
          profile_image_id: image_profile,
          profile_image: image_data
        }
      })
    })
  }

  render () {
    const { navigation } = this.props
    const users = navigation.getParam('user', 'NO ITEM')
    // console.log('users :', users);
    return (
      <KeyboardAvoidingView style={{flex:1}}
                            keyboardVerticalOffset={Platform.OS == 'ios' ? 75 : 0}
                            behavior={Platform.OS == 'ios' ? 'padding' : ''}
                            ref={(view) => {this.scrollView = view;}}
      >
      <View style={{ flex: 1, backgroundColor: '#00420A'}}>
        <BackgroundImage_RegisterForm>
          <ScrollView style={{ flex: 1, height: '100%' }}>
            <View style={{ flexDirection: 'column', flex: 1}}>
              <View>
                <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
                  // flex: 1,
                  width: null,
                  height: null,
                  resizeMode: 'cover'
                }}>
                  <View style={{ paddingVertical: 20, alignItems: 'center' }}>
                    <View>
                      <TouchableOpacity
                        style={{
                          backgroundColor: '#FFF',
                          borderRadius: 50, padding: 5,
                          justifyContent: 'center',
                          alignItems: 'center',
                          position: 'absolute',
                          right: '0%',
                          top: '0%',
                          zIndex: 1
                        }}
                        onPress={() => {
                          // this.onImagePick()
                          ActionSheet.showActionSheetWithOptions({
                              options: ACTIONSHEET_BUTTONS,
                              cancelButtonIndex: CANCEL_INDEX,
                              // destructiveButtonIndex: DESTRUCTIVE_INDEX,
                              // tintColor: 'blue'
                            },
                            (buttonIndex) => {
                              // console.log('button clicked :', buttonIndex)
                              if (buttonIndex == 0) {
                                this.onTakeCamera()
                              } else if (buttonIndex == 1) {
                                this.onImagePick()
                              }
                            })
                        }}>
                        <Icon name={'ic_outline_camera'} size={20} color={'#8BC34A'}/>
                      </TouchableOpacity>
                      <Image
                        style={{width: 120, height: 120, borderRadius: 60, borderColor: 'white', borderWidth: 2}}
                        source={{ uri: this.state.image_url && this.state.image_url.uri ? this.state.image_url.uri : ''}}
                      />
                    </View>
                  </View>
                </LinearGradient>
              </View>

              <View style={{ flexDirection: 'column' , padding: 15, paddingTop: 5, paddingBottom: 0,}}>
                <View>
                  <Text style={styles.headerTitle}>{t('profile')}</Text>
                  <View style={styles.row}>
                    <CustomInput
                      labelName={t('fullname')}
                      style={styles.register_input}
                      labelColor={'white'}
                      placeholderTextColor={'white'}
                      value={this.state.user.name}
                      onChangeText={(text) => {
                        this.setState({
                          user: {
                            ...this.state.user,
                            name: text,
                            name_th: text
                          }
                        })
                      }}/>
                  </View>
                  <View style={styles.row}>
                    <CustomInput
                      style={styles.register_input}
                      labelColor={'white'}
                      placeholderTextColor={'white'}
                      labelName={t('email')}
                      value={this.state.user.email}
                      onChangeText={(text) => {
                        this.setState({
                          user: {
                            ...this.state.user,
                            email: text
                          }
                        })
                      }}/>
                  </View>
                  {/*<View style={styles.row}>
                  <View style={styles.row_grow_first}>
                   <View
                      style={{
                        flexGrow: 1,
                        flexDirection: 'row',
                        height: 40,
                        maxHeight: 48,
                        minHeight: 40,
                        paddingHorizontal: 5,
                        backgroundColor: 'rgba(255,255,255,0.3)',
                        borderRadius: 30
                      }}
                    >
                      <View
                        style={{
                          justifyContent: 'center',
                          paddingLeft: 5,
                          paddingRight: 5
                        }}
                      >
                        <Text
                          style={{
                            color: 'white'
                          }}
                        >
                          {t('gender')}
                        </Text>
                      </View>
                      <View style={{ flex: 1,alignItems: Platform.OS == 'ios' ? 'flex-end' : 'stretch'}}>
                        <Picker
                          mode="dropdown"
                          style={{
                            height: 40,
                            color: 'white',
                          }}
                          textStyle={{color:'white',fontFamily: 'Prompt-Regular',fontSize:14,textAlign:'right'}}
                          itemStyle={{color:'white',fontFamily: 'Prompt-Regular',fontSize:14}}
                          itemTextStyle={{color:'black',fontFamily: 'Prompt-Regular',fontSize:14}}
                          labelName={t('gender')}
                          placeholder={t('male') +"/"+ t('female')}
                          selectedValue={this.state.user.gender}
                          onValueChange={e => {
                            // console.log('check gender +++++++++++++++ ',e);
                            this.setState({
                              user: {
                                ...this.state.user,
                                gender: e
                              }
                            })
                          }}
                        >
                          <Picker.Item label={t('male')} value="male"/>
                          <Picker.Item label={t('female')} value="female"/>
                        </Picker>
                      </View>
                    </View>
                  </View>
                </View>*/}
                  {/*<View style={styles.row}>
                  <View style={styles.row_grow}>
                    <CustomDatePicker titleText={t('birth_date')} dateText={moment(this.state.user.show_birth_date).add(543, 'years').format('DD-MM-YYYY')} handleDate={(data) => {
                      this.setState({
                          user: {
                            ...this.state.user,
                            birth_date: moment(data).format('YYYY-MM-DD'),
                            show_birth_date: moment(data).format('YYYY-MM-DD')
                          }
                        })}}/>
                  </View>
                </View>*/}
                  {/*<View style={styles.row}>
                  <CustomInput
                    style={styles.register_input}
                    labelColor={'white'}
                    placeholderTextColor={'white'}
                    labelName={t('citizen_id')}
                    value={this.state.user.tax_id}
                    onChangeText={(text) => {
                      this.setState({
                        user: {
                          ...this.state.user,
                          tax_id: text
                        }
                      })
                    }}/>
                </View>*/}
                  <View style={styles.row}>
                    <CustomInput
                      style={styles.register_input}
                      labelColor={'white'}
                      placeholderTextColor={'white'}
                      labelName={t('phone')}
                      value={this.state.user.mobile}
                      onChangeText={(text) => {
                        this.setState({
                          user: {
                            ...this.state.user,
                            mobile: text
                          }
                        })
                      }}/>
                  </View>
                  {/*<Text style={styles.headerTitle}>{t('accom_info')}</Text>*/}
                  {/*<View style={styles.row}>
                  <View
                    style={{
                      flexGrow: 1,
                      flexDirection: 'row',
                      height: 40,
                      maxHeight: 48,
                      minHeight: 40,
                      paddingHorizontal: 5,
                      backgroundColor: 'rgba(255,255,255,0.3)',
                      borderRadius: 30
                    }}
                  >
                    <View
                      style={{
                        justifyContent: 'center',
                        paddingLeft: 5,
                        paddingRight: 5
                      }}
                    >
                      <Text
                        style={{
                          color: 'white'
                        }}
                      >
                        {t('project')}
                      </Text>
                    </View>
                    <View style={{ flex: 1 }}>
                    <Picker
                        style={{
                          color: 'white',
                          height: 40,
                        }}
                        textStyle={{color:'white',fontFamily:'Prompt-Regular',fontSize:14}}
                        labelName={t('project')}
                        placeholder={t('choose_project')}
                        selectedValue={this.state.project_item}
                        onValueChange={e => {
                          // console.log('@@@@@@ project selected --------> ',e);
                          this.setState({
                            project_name: e.name,
                            project_item:e,
                            selected_project: e.id,
                            user: {
                              ...this.state.user,
                              project: e.code,
                            },
                          }, () => {
                            this.getBuildingList()
                          })
                        }}
                      >
                        {this.state.project_list.map((item,index) => {
                          return <Picker.Item label={item.name} value={item} key={'project_'+index}/>
                        })}
                      </Picker>
                    </View>
                  </View>
                </View>*/}
                  {/*<View style={styles.row}>
                <View
                    style={{
                      flexGrow: 1,
                      flexDirection: 'row',
                      height: 40,
                      maxHeight: 48,
                      minHeight: 40,
                      paddingHorizontal: 5,
                      backgroundColor: 'rgba(255,255,255,0.3)',
                      borderRadius: 30
                    }}>
                    <View
                      style={{
                        justifyContent: 'center',
                        paddingLeft: 5,
                        paddingRight: 5
                      }}>
                      <Text
                        style={{
                          color: 'white'
                        }}>
                        {t('building')}
                      </Text>
                    </View>
                    <View style={{ flex: 1 }}>
                      <Picker
                        // mode="dropdown"
                        style={{
                          color: 'white',
                          height: 40,
                        }}
                        textStyle={{color:'white',fontFamily:'Prompt-Regular',fontSize:14}}
                        labelName={t('building')}
                        placeholder={t('choose_project')}
                        selectedValue={this.state.user.building != null && this.state.user.building}
                        onValueChange={e => {
                          this.setState({
                            user: {
                              ...this.state.user,
                              building: e
                            }
                          })
                        }}>
                        {this.state.building_list.map((item,index) => {
                          return <Picker.Item label={item.room_build} value={item.room_build} key={'building_'+index}/>
                        })}
                      </Picker>
                    </View>
                  </View>
                  <View style={styles.row_grow}>
                    <CustomInput
                      style={styles.register_input}
                      labelColor={'white'}
                      placeholderTextColor={'white'}
                      labelName={t('room2')}
                      placeholder={t('room_no')}
                      placeholderTextColor={'#FFFFFF40'}
                      value={this.state.user.room}
                      onChangeText={(text) => {
                        this.setState({
                          user: {
                            ...this.state.user,
                            room: text
                          }
                        })
                      }}/>
                  </View>
                </View>*/}

                  <Text style={styles.headerTitle}>{t('change_password')}</Text>
                  <View>
                    <View style={styles.row}>
                      <CustomInput
                        label
                        style={styles.register_input}
                        labelColor={'white'}
                        labelName={t('new_password')}
                        secureTextEntry={true}
                        placeholderTextColor={'#FFFFFF40'}
                        placeholder={t('enter_new_password')}
                        value={this.state.user.password}
                        onChangeText={(text) => {
                          this.setState({
                            user: {
                              ...this.state.user,
                              password: text
                            }
                          })
                        }}/>
                    </View>
                    <View style={styles.row}>
                      <CustomInput
                        style={styles.register_input}
                        labelColor={'white'}
                        labelName={t('confirm_password')}
                        secureTextEntry={true}
                        placeholderTextColor={'#FFFFFF40'}
                        placeholder={t('enter_confirm_password')}
                        value={this.state.user.confirm_password}
                        onChangeText={(text) => {
                          this.setState({
                            user: {
                              ...this.state.user,
                              confirm_password: text
                            }
                          })
                        }}/>
                    </View>
                  </View>
                </View>

                <View>
                  <View style={styles.buttons}>
                    <View style={styles.row_grow}>
                      <CustomButton style={styles.btn_next_register} title={t('complete')}
                                    sizeText={14}
                                    onPress={this.edit_profile}
                      />
                    </View>
                  </View>
                </View>
              </View>
            </View>
          </ScrollView>
        </BackgroundImage_RegisterForm>
      </View>
      </KeyboardAvoidingView>
    )
  }
}

const styles = {
  container: {
    flex: 1,
    flexDirection: 'column',
    height: GetWidthHeightDevice.HeightDevice,
  },
  logo: {
    height: '20%',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  form: {
    flex: 1,
    padding: 15,
    paddingTop: 5,
    paddingBottom: 0,
  },
  row: {
    flexDirection: 'row',
    marginBottom: 5,
  },
  form_address: {
    padding: 10,
    paddingBottom: 0,
  },
  step_indicator: {
  },
  buttons: {
    flexDirection: 'row',
    marginTop: 15,
    bottom: 10
  },
  row_grow: {
    flexGrow: 1,
  },
  row_grow_first: {
    flexGrow: 1,
  },
  headerTitle: {
    color: '#8BC34A',
    marginVertical: 5,
    marginTop: 10

  }, btn_next_register: {
    backgroundColor: '#145EB3'
  }, register_input: {
    backgroundColor: 'rgba(255,255,255,0.3)',
    borderRadius: 30,
  }
};

const mapDisPatchToProps = state => {
  return state.app
};
const setUser = dispatch => bindActionCreators({ appSetDevice, appSetUser, appCleanUser }, dispatch)
export default connect(mapDisPatchToProps, setUser)(EditProfileScreen)
