import React, {Component} from 'react'
import {FlatList, View, TouchableOpacity, RefreshControl, ScrollView, ActivityIndicator} 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 moment from "moment";
import { t } from '../../utils/i18n';

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) {
    read_notification(item.id).then(res => {
      console.log('read noti => ', res.data.message)
    })
  }

  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, 1).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(source_type) {
    let type = 'ข่าวใหม่';
    switch (source_type) {
      case 'news':
        type = t('latest_news');
        break;
      case 'rooms':
        type = t('new_room');
        break;
      case 'promotion':
        type = t('latest_promotion');
        break;
      default:
        type = t('latest_news');
        break;
    }

    return type;
  }

  getDateNoti(date) {
    let d = moment(date).format('D')
    let m = moment(date).format('MM')
    let y = parseInt(moment(date).format('Y')) + 543
    let new_month = 'ม.ค.';
    let new_date = d + ' ' + new_month + ' ' + y;
    switch (m) {
      case '01':
        new_month = 'ม.ค.';
        break;
      case '02':
        new_month = 'ก.พ.';
        break;
      case '03':
        new_month = 'มี.ค.';
        break;
      case '04':
        new_month = 'เม.ย.';
        break;
      case '05':
        new_month = 'พ.ค.';
        break;
      case '06':
        new_month = 'มิ.ย.';
        break;
      case '07':
        new_month = 'ก.ค.';
        break;
      case '08':
        new_month = 'ส.ค.';
        break;
      case '09':
        new_month = 'ก.ย.';
        break;
      case '10':
        new_month = 'ต.ค.';
        break;
      case '11':
        new_month = 'พ.ย.';
        break;
      case '12':
        new_month = 'ธ.ค.';
        break;
      default:
        new_month = 'ม.ค.';
        break;
    }

    new_date = d + ' ' + new_month + ' ' + y;
    return new_date;
  }

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

  renderFooter() {
    if (!this.state.refreshing) return null;
    return (
      <ActivityIndicator
        style={{ color: '#000' }}
      />
    );
  }

  _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}>
              <FlatList
                data={this.state.new_noti}
                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)}
                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.is_read === false ? styles.isReadFalse : styles.isReadTrue]}
                  >
                    <View style={styles.viewimages} key={index}>
                      <Image style={styles.image} //source={{uri: rowData.image}}
                             source={item.url ? {uri: item.url} : require('../../../assets/images/news_test.png')}
                             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.source &&
                            item.source.content_type &&
                              item.source.content_type == 'general' ? t('latest_news') : t('latest_promotion')
                          }
                        </Text>
                        <Text numberOfLines={2} style={{fontSize: 14, color: 'black', marginBottom: 3,}}>
                          {item.title}
                        </Text>

                        <Text style={{fontSize: 10, color: 'rgba(0, 0, 0, 0.5)',}}>
                          {this.getDateNoti(item.notified_at)}
                        </Text>
                      </View>
                    </View>
                  </TouchableOpacity>
                }
              />
            </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)
