import React, { Component } from 'react';
import {View, TouchableOpacity, KeyboardAvoidingView, FlatList, StyleSheet, TextInput, Alert, Image, Platform, Keyboard} from 'react-native';
import Text from '../../components/Text';
import moment from "moment";
import Color from '../../../src/color';
import {Button} from "native-base";
import {getConversation, postConversation} from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import { t } from '../../utils/i18n';
import ImageView from 'react-native-image-view';
// import 'moment/locale/th';
//moment.locale('th');

export default class QuestionScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      message_list:[],
      text_input:'',
      isSending: false,
      keyboardAndroidOffset: 0,
      isImageViewVisible: false,
      media_url: null
    };
    this.sendQuestion = this.sendQuestion.bind(this)
    this.getMessageList = this.getMessageList.bind(this)
  }

  componentWillUnmount = () => {
    if(this.props && this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.getNotification){
      this.props.navigation.state.params.getNotification()
    }
  }

  componentDidMount = () => {
    this.props.navigation.setParams({onRefreshMessage: this.getMessageList})
    this.getMessageList()
    // Keyboard.addListener('keyboardDidShow', this._keyboardDidShow)
  };

  componentWillUnmount() {
    if(this.props && this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.getNotification){
      this.props.navigation.state.params.getNotification()
    }
  }
  /*_keyboardDidShow = (e) => {
    this.setState({
      keyboardAndroidOffset: parseInt(e.endCoordinates.height)
    })
  };*/

  getMessageList(loading = true){
    this.setState({
      isLoading: loading
    })
    getConversation()
    .then(res => {
      if(res.ok){
        console.log('check response conversation --------> ',res.data)
        this.setState({
          message_list: res.data.data
        },() => {
          this._flatlistRef.scrollToEnd()
        })
      }

      this.setState({
        isLoading: false,
      })
    })
  }

  sendQuestion(){
    if(this.state.text_input !== ''){
      this.setState({
        // isLoading: true
        isSending: true
      }, () => {
        let param = {
          message: this.state.text_input
        }
        postConversation(param)
          .then(res => {
            if(res.ok){
              // Alert.alert('รับคำถามเรียบร้อย', 'ทางเราได้รับคำถามของคุณแล้ว ขอบคุณค่ะ',[{text: t('ok'), onPress: () => this.getMessageList()}])
              this.setState({
                text_input: ''
              }, () => {
                this.getMessageList(false)
                let _this = this;
                setTimeout(function () {
                  _this.setState({
                    isSending: false
                  })
                }, 1000)
              })
            }else{
              Alert.alert(t('error_occurred'), t('try_again'))
              this.setState({
                isSending: false
              })
            }

            console.log('check data ============== ',res);
          })

      })
    }

  }

  _keyExtractor = (item, index) => 'nessage_item_'+index;

  _renderItem = ({item}) => (
    <View style={{padding:16,backgroundColor: item.sender_type == 'admin' ? '#EAEAF4' : '#E1EDD2' }}>
      <Text style={{fontSize: 12, color:'#00000080', textAlign: item.sender_type == 'admin' ? 'left' : 'right', marginBottom: 5}}>{moment(item.created_at).format('DD MMMM YYYY, HH:mmน.')}</Text>
      <Text style={{fontSize: 14, color:'#00420A', fontWeight: '500' , textAlign: item.sender_type == 'admin' ? 'left' : 'right'}}>{item.sender_type == 'admin' ? t('admin_project') : t('me')}</Text>
      <Text style={{marginTop:10,fontSize: 14, textAlign: item.sender_type == 'admin' ? 'left' : 'right'}}>{item.content}</Text>
        {
          item.media && item.media.length > 0 ?
            <TouchableOpacity onPress={() => {this.setState({isImageViewVisible: true, media_url: item.media.url})}}>
              <Image style={styles.image} source={{uri: item.media[0].url ? item.media[0].url : item.media[0]}} />
            </TouchableOpacity>
            : null
        }
    </View>
  );

  render() {
    return (
      <KeyboardAvoidingView style={{flex: 1,backgroundColor:'white'}} behavior={Platform.OS == 'ios'? 'padding' : ''}
                            keyboardVerticalOffset={Platform.OS == 'ios'? 85 : 0}
                            ref={(view) => {this.scrollView = view;}}
      >
        <View style={{flex:1,padding:16}}>
          <ImageView
            images={[{source: {uri: this.state.media_url != null && this.state.media_url ? this.state.media_url : '' }}]}
            imageIndex={0}
            isVisible={this.state.isImageViewVisible}
            animationType={'fade'}
            onClose={() => {this.setState({isImageViewVisible: false, media_url: null})}}
          />
          <FlatList
              ref={c => this._flatlistRef = c}
              data={this.state.message_list}
              extraData={this.state}
              keyExtractor={this._keyExtractor}
              renderItem={this._renderItem}
              ItemSeparatorComponent={() => {
                return <View style={{width: '100%',height: 8}}>
                </View>
              }}
              onContentSizeChange={()=> this._flatlistRef.scrollToEnd()}
              ListEmptyComponent={() => {
                return <View style={{alignItems:'center'}}>
                  <Text>{t('no_chat')}</Text>
                </View>
              }}
              style={{}}/>
        </View>
        <View style={{borderTopWidth:1,borderColor:'#00000080', marginBottom: 15}}>
          <TextInput
            placeholder={t('message')}
            style={[styles.textArea, {color: 'rgba(0,0,0,0.5)'}]}
            value={this.state.text_input}
            multiline={true}
            numberOfLines={4}
            onChangeText={(text) => this.setState({text_input: text})}/>
            <Button block style={{backgroundColor: this.state.isSending ? '#AAAAAA' : '#145EB3', marginHorizontal: 10, marginTop: 15}}
                    disabled={this.state.isSending}
                    onPress={() => {this.sendQuestion()}}>
              <Text style={{color: '#ffffff', fontSize: 14}}>{t('submit_data')}</Text>
            </Button>
        </View>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  textArea: {
    backgroundColor: 'white',
    marginHorizontal: 10,
    paddingHorizontal: 10,
    marginTop: 10,
    paddingVertical: 15,
    height: 72,
    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
  },
  image: {
    width: 150,
    height: 130,
  },
})
