import React, {Component} from 'react'
import {Alert, ScrollView, StyleSheet, TextInput, View, TouchableOpacity, KeyboardAvoidingView, Platform} from 'react-native'
import Image from 'react-native-fast-image'
import Icon from "../../components/Icon";
import {Button} from "native-base";
import {BackgroundImage} from '../../components/BackgroundImage'
import Text from '../../components/Text';
import LinearGradient from 'react-native-linear-gradient';
import GetWidthHeightDevice from '../../components/GetWidthHeightDevice'
import ActionSheet from "react-native-action-sheet";
import ImagePicker from 'react-native-image-crop-picker'
import {postSuggestion, postSuggestionLogin} from '../../api/UserApi';
import { connect } from "react-redux";
import { t } from 'src/utils/i18n'
import IndicatorLoading from '../../components/IndicatorLoading';
let ACTIONSHEET_BUTTONS = [
  t('take_photo'),
  t('from_gallery'),
  t('cancel')
]

let CANCEL_INDEX = 2

class SuggestionScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      suggestionText: null,
      image_list: [],
      isShowAddBtn: true,
      image_selected: {},
      isLoading: false,
      suggestionTitle: null
    };
    this.onImagePick = this.onImagePick.bind(this)
    this.onTakeCamera = this.onTakeCamera.bind(this)
    this.sendDataSuggestion = this.sendDataSuggestion.bind(this)
  }

  sendDataSuggestion() {
    this.setState({
      isLoading: true
    }, () => {
      let param = {
        message: this.state.suggestionText,
        image: this.state.image_selected,
        title: this.state.suggestionTitle
      }
      console.log("param",param);
      if(this.props.user == null && param.message != null && param.title != null && param.title.trim() !== ""){
        postSuggestion(param)
          .then(res => {
            console.log('check response suggestion -----------> ',res)

              Alert.alert(t('feedback_title'), t('feedback_body'),[{text: t('ok'), onPress:() => {
                  this.setState({
                    isLoading: false
                  }, () => {
                this.props.navigation.goBack()
                  })
              }}])
          })
      }else if(this.props.user != null && param.message != null && param.title != null && param.title.trim() !== ""){
        postSuggestionLogin(param)
          .then(res => {
            console.log('check response suggestion -----------> ',res)
            Alert.alert(t('feedback_title'), t('feedback_body'),[{text: t('ok'), onPress:() => {
                this.setState({
                  isLoading: false
                }, () => {
                  this.props.navigation.goBack()
                })
              }}])
          })
      }else{
        console.log('suggestion fails')
        this.setState({
          isLoading: false
        }, () => {
          Alert.alert('ส่งข้อเสนอแนะไม่สำเร็จ', t('required_field'),[{text: t('ok')}])
        })
      }
    })

  }

  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',
      }
      this.setState({
        image_url: {uri: `data:${image.mime};base64,` + image.data, width: image.width, height: image.height},
        images: null,
      }, () => {
        this.setState({
          image_list: this.state.image_list.concat(this.state.image_url),
          image_selected: image_profile,
          isShowAddBtn: false
        })
      })
    }).catch(e => {
        // alert(e)
    })
  }

  onTakeCamera() {
    ImagePicker.openCamera({
      // cropping: true,
      // width: 300,
      // height: 300,
      includeExif: true
    }).then(image => {
      console.log('received image', image)
      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,
      }, () => {
        this.setState({
          image_list: this.state.image_list.concat(this.state.image_url),
          image_selected: image_profile,
          isShowAddBtn: false
        })
      })
    }).catch(e => {
      // alert(e)
    })
  }

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
        <KeyboardAvoidingView style={{flex:1}} keyboardVerticalOffset={Platform.OS == 'ios' ? 75 : 0} behavior={Platform.OS == 'ios' ? "padding" : ""} enabled>
          <ScrollView contentContainerStyle={{flex:1}}>
          <View style={{backgroundColor: 'white'}}>
            <View>
              <Text style={{color: '#00420A', padding: 16, paddingBottom: 5}}>{t('title')}</Text>
              <TextInput
                placeholder={t('suggestion_title')}
                style={styles.textInput}
                onChangeText={(text) => this.setState({suggestionTitle: text})}
                value={this.state.suggestionTitle}/>
            </View>
            <View>
              <Text style={{color: '#00420A', padding: 16, paddingBottom: 5}}>{t('suggestion')}</Text>
              <TextInput
                placeholder={t('write_suggest')}
                style={[styles.textArea, {color: 'rgba(0,0,0,0.5)'}]}
                value={this.state.suggestionText}
                multiline={true}
                numberOfLines={4}
                onChangeText={(text) => this.setState({suggestionText: text})}/>
            </View>
            <View>
              <Text style={{color: '#00420A', padding: 16}}>{t('photo')}</Text>
              <View style={{flexDirection: 'row'}}>
                {
                  this.state.isShowAddBtn &&
                  <TouchableOpacity style={[styles.squareShapeView, {marginTop: 0}]}
                                    onPress={() => {
                                      ActionSheet.showActionSheetWithOptions({
                                          options: ACTIONSHEET_BUTTONS,
                                          cancelButtonIndex: CANCEL_INDEX,
                                        },
                                        (buttonIndex) => {
                                          console.log('button clicked :', buttonIndex)
                                          if (buttonIndex == 0) {
                                            this.onTakeCamera()
                                          } else if (buttonIndex == 1) {
                                            this.onImagePick()
                                          }
                                        })
                                    }}>
                    <Icon active name="ic_add" size={35} color="white"/>
                  </TouchableOpacity>
                }
                {
                  this.state.image_list.map((item, index) => {
                    return <View style={{padding:10}} key={'image_suggest_' + index}>
                      <Image style={{width: 64, height: 64, borderRadius: 5}} source={{uri: item.uri}}/>
                      <TouchableOpacity style={{height: 20, width: 20, backgroundColor: '#00000080', position: 'absolute', right: 2, top: 2, justifyContent: 'center', alignItems: 'center', borderRadius: 10}}
                                        onPress={() => {
                                          this.setState({
                                            image_list: [
                                              ...this.state.image_list.slice(0, index),
                                              ...this.state.image_list.slice(index + 1)
                                            ],
                                            isShowAddBtn: true
                                          })
                                        }}>
                        <Icon active name="ic_add" size={15} color="white" style={{transform: [{rotate: '45deg'}]}}/>
                      </TouchableOpacity>
                    </View>
                  })
                }
              </View>
            </View>
          </View>
          <View style={{flex:1,justifyContent: 'flex-end'}}>
            <Button block style={{backgroundColor: '#145EB3', marginHorizontal: 10, marginVertical: 15}}
                    onPress={() => {
                      this.sendDataSuggestion()
                    }}>
              <Text style={{color: '#ffffff', fontSize: 14}}>{t('submit_data')}</Text>
            </Button>
          </View>
          </ScrollView>
          </KeyboardAvoidingView>
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    height: GetWidthHeightDevice.HeightContainer,
    //backgroundColor: '#FAFAFA'
  },
  formGroup: {
    marginHorizontal: 15,
    marginVertical: 5,
    backgroundColor: '#ffffff',
    width: '93%',
    height: 40,
    borderRadius: 5,
    display: 'flex',
    flexDirection: 'row'
  },
  textInput: {
    backgroundColor: 'white',
    paddingVertical: 15,
    borderRadius: 5,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.25)',
    paddingHorizontal: 10,
    marginHorizontal: 10,
  },
  textArea: {
    backgroundColor: 'white',
    marginHorizontal: 10,
    paddingHorizontal: 10,
    marginVertical: 10,
    paddingVertical: 15,
    height: 100,
    textAlignVertical: 'top',
    borderRadius: 5,
    borderWidth: 1,
    borderColor: 'rgba(0, 0, 0, 0.25)'
  },
  squareShapeView: {
    width: 64,
    height: 64,
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.25)',
    margin: 10
  }
});

const mapDisPatchToProps = state => ({
  user: state.app.user
})

export default connect(mapDisPatchToProps)(SuggestionScreen)
