import React, { Component } from 'react';
import { View, TouchableOpacity, KeyboardAvoidingView, FlatList, StyleSheet, TextInput, Alert , Image } 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 'moment/locale/th';
//moment.locale('th');

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

  componentDidMount = () => {
    this.props.navigation.setParams({onRefreshMessage: this.getMessageList})
    this.getMessageList()
  };

  getMessageList(){
    this.setState({
      isLoading: true
    })
    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(){
    this.setState({
      isLoading: 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: ''
        })
      }else{
        Alert.alert('เกิดข้อผิดพลาด', 'กรุณาลองอีกครั้ง')
      }
      this.setState({
        isLoading: 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'}}>
      <View style={{flexDirection:'row',justifyContent:'space-between'}}>
        <Text style={{fontSize: 14,}}>{item.sender_type == 'admin' ? t('project') : t('me')}</Text>
        <Text style={{fontSize: 12,color:'#00000080'}}>{moment(item.created_at).format('DD MMMM YYYY, HH:mmน.')}</Text>
      </View>
      <Text style={{marginTop:10,fontSize: 14,}}>{item.content}</Text>
      {item.media != null ? <Image style={styles.image} source={{uri: item.media.url}} /> : null}
    </View>
  );

  render() {
    return (
      <KeyboardAvoidingView style={{flex:1,backgroundColor:'white'}} behavior={'padding'}  ref={(view) => {
        this.scrollView = view;
      }}>
        <View style={{flex:1,padding:16}}>
          <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>ไม่มีข้อมูลการสนทนา</Text>
                </View>
              }}
              style={{}}/>
        </View>
        <View style={{borderTopWidth:1,borderColor:'#00000080'}}>
          <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: '#145EB3', marginHorizontal: 10, marginVertical: 15}}
                    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,
  },
})
