import React, { Component } from 'react';
import { View, TouchableOpacity, StyleSheet, RefreshControl, useWindowDimensions } from 'react-native';
import Image from 'react-native-fast-image'
import { FlatList } from 'react-native-gesture-handler';
import Text from '../../components/Text';
import Icon from '../../components/Icon'
import {getObjectMessage, getRoomParcel} from '../../api/UserApi'
import moment from 'moment';
import IndicatorLoading from '../../components/IndicatorLoading';
import { NavigationEvents } from 'react-navigation'
import { t } from 'src/utils/i18n'
import HTML from 'react-native-render-html';
// import 'moment/locale/th';
// moment.locale('th');

export default class MessageObject extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isRefreshing: false,
      isLoading: true,
      message_list:[],
      users:[],
      roomIds:[],
    };

    this.statusText = this.statusText.bind(this)
    this.statusColor = this.statusColor.bind(this)
  }

  componentDidMount() {
    // this.getObject()
    const { navigation } = this.props
    const users_state = navigation.getParam('user', 'NO ITEM')
    this.state.users = users_state
    this.state.roomIds = new Array()
    if(users_state){
      let rooms = users_state.room ? users_state.room : null
      let rooms_list = rooms != null ? rooms.split(",") : []
      var arrayLength = rooms_list.length;
      let self = this;
      for (var i = 0; i < arrayLength; i++) {
        getRoomParcel(rooms_list[i])
          .then(res => {
            if(res.ok){
              let result_data = new Array()
              result_data = res.data.data
              self.state.roomIds.push(result_data.id)
            }
          })
      }
    }
  }

  getObject(){
    this.setState({
      isLoading: true
    }, () => {
      getObjectMessage()
        .then(res => {
          if(res.ok && res.data){
            // let parcel_data = new Array()
            // parcel_data=res.data.data
            // var roomIds = this.state.roomIds
            // var filteredArray = new Array()
            // if(roomIds.length > 0){
            //   filteredArray = parcel_data.filter(function(itm){
            //     return roomIds.indexOf(itm.room_id) > -1;
            //   })
            this.setState({
              message_list: res.data.data,
            })
          }
        })

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


  }

  statusColor(status){
    switch(status){
      case 'PENDING':
        return '#C4C4C4'
      case 'ERROR':
        return '#FF662E'
      case 'WAIT_PICKUP':
      case 'RECEIVE':
        return '#2C7C0B'
      default:
        return '#FF662E'
    }
  }

  statusText(status){
    switch(status){
      case 'PENDING':
        return t('waiting_for_pickup')
      case 'WAIT_PICKUP':
        return t('awaiting_payment')
      case 'RECEIVE':
        return t('paid')
      case 'OTHER':
        return t('other')
      case 'ERROR':
      default:
        return t('contact_front_desk')
    }
  }

  _keyExtractor = (item, index) => 'msg_obj_'+index

  _renderItem = ({item,index}) => (
    <TouchableOpacity onPress={() => {this.props.navigation.navigate('ObjectDetail',{object_id: item.id})}}
      disabled={item.status == 'PENDING' || item.status === 'wait_customer_code' ? false : true}
      style={{opacity:item.status == 'PENDING' ? 0.5 : 1}}>
      <View style={{paddingHorizontal:16, height: 88,backgroundColor:'white',borderWidth:1,borderColor:'#EAEAF4'}}>
        <View style={{flex:1,flexDirection:'row',alignItems:'center', paddingVertical: 20}}>
          <View style={{height: 64,width: 64,justifyContent:'center',marginRight:8}}>
            <Image source={{uri:item.image_past}} style={{height: 64,width: 64,backgroundColor:'black',borderRadius:5}} resizeMode={'cover'}/>
          </View>
          <View style={{flex:1,justifyContent:'center'}}>
            <View style={{flexDirection:'row',justifyContent:'space-between', alignItems: 'center'}}>
              {/* <Text style={styles.textTitle} numberOfLines={1}>{item.parcel_name}</Text> */}
              <HTML html={item.parcel_name} baseFontStyle={{fontFamily: 'Prompt-Regular'}} />
              <Text>

                {((item.code != null) && (item.status != 'PENDING' && item.status != 'OTHER' && item.status != 'ERROR') ) ? t('confirmation_code'): '' }

              </Text>
            </View>
            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
              <Text style={styles.textTitle} numberOfLines={1}>{t('consignee')} : { item.customer_name ? item.customer_name.length > 22 ? item.customer_name.substring(0, 22) + '...' : item.customer_name : "" }</Text>
              <Text style={{fontWeight: 'bold',fontSize: 18}}>

                {((item.code != null)&&(item.status != 'PENDING' && item.status != 'OTHER' && item.status != 'ERROR')) ? item.code: '' }

              </Text>
            </View>
            <View style={{flexDirection:'row',justifyContent:'space-between'}}>
              <View style={{justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                <Icon name='ic_event_note' size={16} style={{marginRight:3}}/>
                <Text>{moment(item.updated_at).format('DD MMMM YYYY')}</Text>
              </View>
              <View style={{justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                <View style={{height: 10,width: 10,borderRadius:5,backgroundColor:this.statusColor(item.status),marginRight:5}}/>
                <Text style={{color:this.statusColor(item.status)}}>{this.statusText(item.status)}</Text>
              </View>
            </View>
          </View>
        </View>
      </View>
    </TouchableOpacity>
  );

  render() {
    return (
      <View style={{flex:1,backgroundColor:'#EEFFD7'}}>
        <NavigationEvents
            onDidFocus={() => {
              this.getObject()
            }}
          />
        <FlatList
         refreshControl={
          <RefreshControl
            refreshing={this.state.isRefreshing}
            onRefresh={this.getObject.bind(this)}
          />
        }
          data={this.state.message_list}
          extraData={this.state}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          style={{flex:1}}
          ListEmptyComponent={() =>
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', margin: 16,padding:16,borderRadius:5,backgroundColor:'white'}}>
              <Text style={{fontSize: 16}}> {t('no_mail_parcel')} </Text>
            </View>
          }
        />
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textTitle:{
    color:'#269A21',
    fontSize: 14,
  }
})
