import React, {Component} from 'react'
import {FlatList, View, TouchableOpacity, RefreshControl, ScrollView, ActivityIndicator, SafeAreaView} from 'react-native'
import Image from 'react-native-fast-image'
import {BackgroundImage} from '../../components/BackgroundImage'
import LinearGradient from 'react-native-linear-gradient';
import Text from '../../components/Text';
import { get_notification, news, read_notification} from '../../api/UserApi'
import {bindActionCreators} from 'redux'
import {appSetNotification} from '../../redux/app/action'
import {connect} from 'react-redux';
import { t } from '../../utils/i18n';
import parseDateLocale from '../../utils/parseDateLocale';
import { NavigationEvents } from "react-navigation";

const injectScript = `
  (function () {
    window.onclick = function(e) {
      e.preventDefault();
      window.postMessage(e.target.href);
      e.stopPropagation()
    }
  }());
`;

class NotificationScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      new_noti: [],
      page: 1,
      last_page: 1,
      refreshing: false,
    }
  }

  _set_read(item) {
    switch (item.source_type) {
      case 'payment_success':
      case 'update_app':
        return false;
      default:
        read_notification(item.id).then(res => {
          this.navigateNotification(item)
        })
    }
  }

  getContentId(item) {
    let data = item.data;
    let dataJson = JSON.parse(data);
    if(dataJson.id){
      return dataJson.id;
    }else {
      return null;
    }
  }

  navigateNotification = (item) => {
    switch (item.source_type) {
      case 'news':
      case 'general':
      case 'promotion':
        this.props.navigation.navigate('NewsDetail', {
          news_id: item.source_id,
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        });
        break;
      case 'parcels':
        if(item.parcel_status === 'PENDING'){
          this.props.navigation.navigate('ObjectDetail', {
            object_id: item.source_id,
            getNotification: () => {
              this.setState({
                page: 1
              }, () => {
                this.getNotification()
              })
            }
          })
        }else {
          this.props.navigation.navigate('Object', {
            user: this.props.user,
            getNotification: () => {
              this.setState({
                page: 1
              }, () => {
                this.getNotification()
              })
            }
          })
        }
        break;
      case 'message':
        this.props.navigation.navigate('Question', {
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        });
        break;
      case 'meter':
        this.props.navigation.navigate('Meter', {
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        });
        break;
      case 'invoice':
      case 'invoice_overdue':
        this.props.navigation.navigate('Payment', {
          payment_id: this.getContentId(item),
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        });
        break;
      case 'repair':
      case 'effect_repair':
      case 'effect_responsible':
      case 'edit_repair':
      case 'appointment_repair':
      case 'cancel_repair':
      case 'success_repair':
      case 'renew_appointment':
        this.props.navigation.navigate('RepairHistoryDetail', {
          repair_id: this.getContentId(item),
          type: item.source_type,
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        })
        break;
      case 'request_contact':
        this.props.navigation.navigate('Question', {
          getNotification: () => {
            this.setState({
              page: 1
            }, () => {
              this.getNotification()
            })
          }
        })
      break;
      default:
        return false;
    }
  }

  componentDidMount() {
    if (this.props.token != null && this.props.user != null) {
      this.setState({
        auth: true,
      })
    } else {
      this.setState({
        auth: false,
      })
    }

    this.setState({
      page: 1,
      refreshing: true
    }, () => {
      this.getNotification()
    })
  }

  getNotification() {
    let user_noti_id = 0;
    if(this.props.user && this.props.user.id){
      user_noti_id = this.props.user.id
    }else if(this.props.device && this.props.device.customer_id){
      user_noti_id = this.props.device.customer_id
    }

    // console.log('user_noti_id => ', user_noti_id)
    if(this.props.token != null){
      get_notification(user_noti_id, this.state.page).then(res => {
        if (res.data) {
          this.setState({
            new_noti: res.data.data,
            page: res.data.current_page,
            refreshing: false,
            last_page: res.data.last_page
          });
        }
      })
    }else{
      this.setState({
        refreshing: false
      })
    }
  }

  componentWillUnmount() {
    let user_noti_id = 0;
    if(this.props.user && this.props.user.id){
      user_noti_id = this.props.user.id
    }else if(this.props.device && this.props.device.customer_id){
      user_noti_id = this.props.device.customer_id
    }
      this.props.appSetNotification(0)
  }

  loadMoreNoti() {
    // console.log('check loadmore -------------> ');
    let user_noti_id = 0;
    if(this.props.user && this.props.user.id){
      user_noti_id = this.props.user.id
    }else if(this.props.device && this.props.device.customer_id){
      user_noti_id = this.props.device.customer_id
    }

    if(parseInt(this.state.page) < parseInt(this.state.last_page) && !this.state.refreshing){
      this.setState({
        page: this.state.page + 1,
        refreshing: true
      }, () => {
        get_notification(user_noti_id, this.state.page).then(res => {
          if (res.data) {
            let listData = this.state.new_noti
            let new_listdata = listData.concat(res.data.data)
            this.setState({
              new_noti: new_listdata,
              page: res.data.current_page,
              refreshing: false,
              last_page: res.data.last_page
            });
          }
        })
      })
    }
  }

  _onRefresh = () => {
    this.setState({refreshing: true, page: 1}, () => {
     this.getNotification()
    });
  }

  getTypeNoti(item) {
    let type = t('latest_news');
    switch (item.source_type) {
      case 'news':
      case 'general':
        type = t('latest_news');
        break;
      case 'rooms':
        type = t('new_room');
        break;
      case 'parcels':
        type = t('new_parcel');
        break;
      case 'promotion':
        type = t('latest_promotion');
        break;
      case 'message':
        type = t('new_message');
        break;
      case 'invoice':
      case 'invoice_overdue':
        type = t('bill_payment');
        break;
      case 'meter':
        type = t('meter_noti');
        break;
      case 'repair':
      case 'effect_repair':
      case 'effect_responsible':
      case 'edit_repair':
      case 'appointment_repair':
      case 'request_contact':
      case 'cancel_repair':
      case 'success_repair':
      case 'renew_appointment':
        type = item.title;
        break;
      case 'update_app':
        type = t('update_app');
        break;
      case 'payment_success':
        type = t('payment_success');
        break;
      default:
        type = '';
        break;
    }

    return type;
  }

  getStatusParcel (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');
    }
  }

  displayParcelContent (data) {
    console.log('data  >>> ', JSON.parse(data.data))
    if(data.parcel_status){
      return t('status') + ' : ' + this.getStatusParcel(data.parcel_status)
    }
    return '';
  }

  renderSeparator() {
    return (
      <View
        style={{
          height: 2,
          width: '100%',
          backgroundColor: '#CED0CE'
        }}
      />
    );
  }

  renderFooter() {
    if (!this.state.refreshing) return null;
    return (
      <ActivityIndicator
        size="large"
        color={'white'}
      />
    );
  }

  getImageCover = (item) => {
    if (item.image_path) {
      return {uri: item.image_path};
    } else {
      switch (item.source_type) {
        case 'invoice':
          return require('../../../assets/images/invoice_icon.png');
        case 'invoice_overdue':
          return require('../../../assets/images/invoice_overdue_icon.png');
        case 'meter':
          return require('../../../assets/images/meter_icon.png');
        case 'repair':
        case 'effect_repair':
        case 'effect_responsible':
        case 'edit_repair':
        case 'request_contact':
        case 'cancel_repair':
        case 'renew_appointment':
          return require('../../../assets/images/repair_noti.png');
        case 'appointment_repair':
          return require('../../../assets/images/appointment_repair.png');
        case 'success_repair':
          return require('../../../assets/images/success_repair.png');
        default:
          return require('../../../assets/images/logo_5.png');
      }
    }
  }

  getContent = (item) => {
    switch (item.source_type) {
      // case 'parcels':
      //   return this.displayParcelContent(item);
      case 'message':
        if(item && item.source && item.source.media){
          console.log('media >> ', item.source.media)
          return <Image style={styles.image} source={item && item.source && item.source.media ? {uri: item.source.media} : require('../../../assets/images/default_small.png')}/>;
        }else {
          return item.content;
        }
      default:
        return item.content;
    }
  }

  _keyExtractorNewNoti = (item, index) => 'new_noti_'+index

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
          {/*<ScrollView contentContainerStyle={styles.contentContainer}
                      refreshControl={
                        <RefreshControl
                          refreshing={this.state.refreshing}
                          onRefresh={this._onRefresh}
                        />
                      }
          >*/}
          <View style={styles.container}>
            <NavigationEvents
              onWillFocus={payload => {
                this._onRefresh()
              }}
            />
            <SafeAreaView style={styles.container}>
              <FlatList
                data={this.state.new_noti}
                refreshing={true}
                refreshControl={
                  <RefreshControl
                    refreshing={this.state.refreshing}
                    onRefresh={this._onRefresh}
                  />
                }
                keyExtractor={this._keyExtractorNewNoti}
                ListEmptyComponent={() =>
                  <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', margin: 16,padding:16,borderRadius:5,backgroundColor:'white'}}>
                    <Text style={{fontSize: 16}}> {t('no_notification')} </Text>
                  </View>
                }
                ItemSeparatorComponent={this.renderSeparator}
                ListFooterComponent={this.renderFooter.bind(this)}
                onEndReachedThreshold={0.01}
                onEndReached={this.loadMoreNoti.bind(this)}
                renderItem={({item, rowData, index}) =>
                  <TouchableOpacity
                    onPress={() => {
                      this._set_read(item)
                      /*this.props.navigation.navigate('NewsDetail', {
                        news_id: item.source_id,
                        getNotification: () => this.getNotification()
                      })*/
                    }}
                    key={index}
                    delayPressIn={50}
                    activeOpacity={0.8}
                    style={[ item && item.is_read === false ? styles.isReadFalse : styles.isReadTrue]}
                  >
                    <View style={styles.viewimages} key={index}>
                      <Image style={styles.image} //source={{uri: rowData.image}}
                             source={this.getImageCover(item)}
                             defaultSource={require('../../../assets/images/default_small.png')}
                      />
                      <View style={styles.viewcontainer}>
                        <Text style={{fontSize: 14, color: '#145EB3', marginBottom: 3,}}>
                          {/*{this.getTypeNoti(item.source_type)}*/}
                          {
                           item && item.source_type && this.getTypeNoti(item)
                          }
                        </Text>
                        <Text
                              numberOfLines={item.source_type === 'payment_success' ? 0 : 3}
                              style={{fontSize: 14, color: 'black', marginBottom: 3,}}>
                          {this.getContent(item)}
                        </Text>
                        <Text style={{fontSize: 10, color: 'rgba(0, 0, 0, 0.5)',}}>
                          { item && item.notified_at && parseDateLocale(item.notified_at, 'D MMM Y, HH:mm')}
                        </Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                }
              />
            </SafeAreaView>
          </View>
          {/*</ScrollView>*/}
        </BackgroundImage>
      </LinearGradient>
    )
  }
}

const styles = {
  container: {
    flex: 1,
  },
  contentContainer: {
    paddingVertical: 0,
  },
  isReadFalse: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#E1EDD2',
    borderBottomColor: '#7CBB33',
    borderBottomWidth: 1
  },
  isReadTrue: {
    flex: 1,
    flexDirection: 'row',
    backgroundColor: '#ffffff',
    borderBottomColor: 'rgba(0, 0, 0, 0.25)',
    borderBottomWidth: 1
  },
  viewimages: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-start',
    marginBottom: 3
  },
  image: {
    width: 50,
    height: 50,
    borderRadius: 5,
    marginLeft: 16,
    marginTop: 16
  },
  viewcontainer: {
    flex: 1,
    justifyContent: 'center',
    marginLeft: 5,
    padding: 12
  },
  text_emply_noti: {
    marginTop: 10,
    // fontFamily: Fonts.KrungthaiRegular,
    fontSize: 14,
    lineHeight: 22,
    color: 'rgba(0, 0, 0, 0.5)',
    alignItems: 'center'
  }
}
const mapDisPatchToProps = state => {
  return state.app
}

const countNotification = dispatch => bindActionCreators({ appSetNotification }, dispatch)
export default connect(mapDisPatchToProps, countNotification)(NotificationScreen)
