import React, { Component, Fragment } from 'react'
import {
  View, ScrollView, Dimensions, TouchableOpacity, StyleSheet, FlatList, RefreshControl, Animated, ActivityIndicator, Platform, Alert, Modal
} from 'react-native'
import Image from 'react-native-fast-image'
import ImageBackground from 'react-native-fast-image'
import Icon from '../../components/Icon'
import { Card, Body, Badge, ListItem, Left, Right, } from 'native-base'
import { BackgroundImage_RegisterForm } from '../../components/BackgroundImage_RegisterForm'
import LinearGradient from 'react-native-linear-gradient'
import { BackgroundImage } from '../../components/BackgroundImage'
import Text from '../../components/Text'
import { NavigationEvents } from 'react-navigation'
import {
  getNews,
  getNewsPage,
  getUserProfile,
  getNewsByProject,
  login,
  registerDevice,
  setPaymentLater,
  setFillInMeterLater,
  checkPaymentMeter } from '../../api/UserApi';
import { clearToken } from '../../api/api'
import { bindActionCreators } from 'redux'
import {
  appSetDevice,
  appSetPushToken,
  appSetToken,
  appSetUser,
  appCleanToken,
  appCleanUser,
  appSetNotification,
  appSetProjectID,
  appCleanProjectID
} from '../../redux/app/action'
import { connect } from 'react-redux'
import moment from 'moment'
import IndicatorLoading from '../../components/IndicatorLoading'
import { loginWithFacebook } from '../../components/FacebookUtils'
import { signinApple } from '../../components/AppleAuth'
import parseDateLocale from '../../utils/parseDateLocale'
import { from } from 'rxjs'
//import Slideshow from 'react-native-image-slider-show';
import appleAuth, {
  AppleButton,
} from '@invertase/react-native-apple-authentication';

import { t, locale } from '../../utils/i18n'
import messaging from "@react-native-firebase/messaging";
import {store} from '../../redux/store';

const { height, width } = Dimensions.get('window')
console.disableYellowBox = true

function PopupNotiElectric({isVisible, onPress, onCancel, onPressLater, pending_payment, due_at_payment}) {
  return <Modal visible={isVisible} transparent={true} animationType="none" key="popup-noti-electric">
    <View style={styles.popupNotiContainer}>
      <View style={styles.popupNoti}>
        <View style={{width: '100%', alignItems: 'center'}}>
          <Icon name='ic_shop_receive' color='#FF9500' size={70} style={{marginBottom: 10, width: '100%', textAlign: 'center'}}/>
          <Text style={[{color: '#FF9500', marginBottom: 10, fontSize: 16}, styles.TextFont]}>{t('have_outstanding_balance')}</Text>
          <View style={styles.costText}>
            <Text style={[{fontSize: 25, fontWeight: '500', textAlign: 'center'}, styles.TextFont]}>{pending_payment}</Text>
            <Text style={[{color: '#8A8A8F', fontSize: 18, fontWeight: '400', position: 'absolute', right: 15, bottom: 8}, styles.TextFont]}>{t('baht')}</Text>
          </View>
          <Text style={[{color: '#FF9500', marginBottom: 10, textAlign: 'center' , fontSize: 14}, styles.TextFont]}>{t('please_pay_within')} {moment(due_at_payment).add('543', 'y').format('DD/MM/YYYY')}</Text>

          <TouchableOpacity onPress={onPress} style={{width: '100%', marginTop: 10}}>
            <Badge style={styles.badgeSubmit}>
              <Text style={[{color: 'white', paddingVertical: 10, fontSize: 16}, styles.TextFont]}>{t('pay_now')}</Text>
            </Badge>
          </TouchableOpacity>
          <TouchableOpacity onPress={onPressLater} style={{width: '100%'}}>
            <Badge style={[styles.badgeCancel, {paddingTop: 5}]}>
              <Text style={[{color: 'rgba(0, 0, 0, 0.5)', fontSize: 16}, styles.TextFont]}>{t('later')}</Text>
            </Badge>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  </Modal>
}

function PopupOverDue({isVisible, onPress, onCancel, onPressLater, pending_payment}) {
  return <Modal visible={isVisible} transparent={true} animationType="none">
    <View style={styles.popupNotiContainer}>
      <View style={styles.popupNoti}>
        <View style={{width: '100%', alignItems: 'center', position: 'relative'}}>
          <Icon name='ic_shop_receive' color='#FF2D55' size={70} style={{marginBottom: 10}}/>
          <TouchableOpacity onPress={onPressLater} style={{position: 'absolute', right: 0, top: -10}}>
            <Text style={[{color: 'rgba(0, 0, 0, 0.5)', fontSize: 20}, styles.TextFont]}>{t('close')}</Text>
          </TouchableOpacity>
          <Text style={[{color: '#FF2D55', marginBottom: 10, fontSize: 16}, styles.TextFont]}>{t('payment_overdue')}</Text>
          <View style={styles.costText}>
            <Text style={[{fontSize: 25, fontWeight: '500', textAlign: 'center'}, styles.TextFont]}>{pending_payment}</Text>
            <Text style={[{color: '#8A8A8F', fontSize: 18, fontWeight: '400', position: 'absolute', right: 15, bottom: 8}, styles.TextFont]}>{t('baht')}</Text>
          </View>
          <Text style={[{color: '#FF2D55', fontSize: 14, textAlign: 'center'}, styles.TextFont]}>{t('outstanding_balance_past_due')}</Text>
          {/*<Text style={[{color: '#FF2D55', fontSize: 14, textAlign: 'center'}, styles.TextFont]}>กรุณาดำเนินการชำระหนี้ตอนนี้</Text>*/}
          <Text style={[{color: '#FF2D55', marginBottom: 15, fontSize: 14, textAlign: 'center'}, styles.TextFont]}>{t('contact_front')}</Text>

          <TouchableOpacity onPress={onPress} style={{width: '100%'}}>
            <Badge style={styles.badgeSubmit}>
              <Text style={[{color: 'white', paddingVertical: 10, fontSize: 16}, styles.TextFont]}>{t('ok')}</Text>
            </Badge>
          </TouchableOpacity>
         {/* <TouchableOpacity onPress={onPressLater}>
            <Badge style={[styles.badgeCancel, {paddingTop: 5}]}>
              <Text style={[{color: 'rgba(0, 0, 0, 0.5)', fontSize: 16}, styles.TextFont]}>ภายหลัง</Text>
            </Badge>
          </TouchableOpacity>*/}
        </View>
      </View>
    </View>
  </Modal>
}

function PopupNotiFillInMeter({isVisible, onPress, onCancel, onPressLater, notified_meter_at}) {
  return <Modal visible={isVisible} transparent={true} animationType="none" key="popup-noti-meter">
    <View style={styles.popupNotiContainer}>
      <View style={[styles.popupNoti, {paddingHorizontal: 15}]}>
        <View style={{width: '100%', alignItems: 'center'}}>
          {/*<Icon name='ic_shop_receive' color='#00420A' size={60} style={{marginBottom: 10}}/>*/}
          <Image source={require('../../../assets/images/meter_noti_image.png')} style={{width: 70, height: 70 }} resizeMode={'contain'}/>
          <Text style={[{color: '#00420A', marginVertical: 5, fontSize: 16}, styles.TextFont]}>{t('attach_meter')}</Text>
          <Text style={[{color: '#00420A', marginVertical: 5, fontSize: 13, textAlign: 'center'}, styles.TextFont]}>{t('by_due_date')} {notified_meter_at}</Text>
          <Text style={[{color: '#00420A', marginVertical: 5, fontSize: 13, textAlign: 'center', marginBottom: 15}, styles.TextFont]}>{t('sorry_send_data')}</Text>

          <TouchableOpacity onPress={onPress} style={{width: '100%'}}>
            <Badge style={styles.badgeSubmit}>
              <Text style={[{color: 'white', paddingVertical: 10, fontSize: 16}, styles.TextFont]}>{t('enter_info')}</Text>
            </Badge>
          </TouchableOpacity>
          <TouchableOpacity onPress={onPressLater}>
            <Badge style={[styles.badgeCancel, {paddingTop: 5}]}>
              <Text style={[{color: 'rgba(0, 0, 0, 0.5)', fontSize: 16}, styles.TextFont]}>{t('later')}</Text>
            </Badge>
          </TouchableOpacity>
        </View>
      </View>
    </View>
  </Modal>
}

class NewsScreen extends Component {
  constructor (props) {
    super(props)
    this.state = {
      isLoading: false,
      refreshing: false,
      auth: null,
      position: 0,
      user: {
        point: 0
      },
      interval: null,
      news_head: [{
        title: t('loading_news'),
        content: t('loading_news'),
        date: t('loading_news'),
        is_new: false
      }],
      new_all: [{
        title: t('loading_news'),
        content: t('loading_news'),
        date: t('loading_news'),
        is_new: false
      }],
      due_at: '',
      pending_payment: 0,
      noti_count: 0,
      isFirstTime: true,
      user_point: 0,
      user_project_id: 0,
      isBilling: false,
      isMeter: false,
      isShipping: false,
      scrollY: new Animated.Value(0),
      loadMore: false,
      loadPage: 1,
      last_page: 1,
      isLoadmore: false,
      fb_is_link: false,
      email: '',
      visibleNotiElectric: false,
      visibleNotiOverDue: false,
      visibleNotiMeter: false,
      payment_id: null,
      is_notified_electric: false,
      is_notified_before_due:false,
      is_notified_overdue: false,
      is_notified_meter: false,
      notified_meter_at: moment().format('DD MMM YYYY'),
      due_at_payment: moment().format('DD/MM/YYYY')
    }

    this._onCarouselScroll = this._onCarouselScroll.bind(this)
    this.initData = this.initData.bind(this)
  }

  checkNotifiedPopup = () => {
    if (this.props.user) {
      checkPaymentMeter()
        .then(res => {
          if (res.data && res.data.success) {
            this.setState({
              is_notified_electric: res.data.is_notified_electric,
              is_notified_meter: res.data.is_notified_meter,
              is_notified_overdue: res.data.is_notified_overdue,
              notified_meter_at: res.data.notified_meter_at,
              payment_id: res.data.payment_id,
              pending_payment: res.data.pending_payment != null ? res.data.pending_payment : 0,
              due_at_payment: res.data.payment && res.data.payment.due_at ? res.data.payment.due_at : null,
            }, () => {
              setTimeout(() => {
                console.log('pending payment >>> ', parseInt(this.state.pending_payment))
                this.setState({
                  visibleNotiElectric: this.state.is_notified_overdue ? false : this.state.is_notified_electric && parseInt(this.state.pending_payment) > 0,
                  visibleNotiMeter: ((this.state.is_notified_electric && parseInt(this.state.pending_payment) > 0) || this.state.is_notified_overdue) === true ? false : this.state.is_notified_meter,
                  visibleNotiOverDue: this.state.is_notified_overdue,
                })
              }, 1000)
            })
          }
        })
    }
  }

  async getUser () {
    if (this.props.token != null) {
      return await getUserProfile()
        .then(async res => {
          if (res.ok) {
            console.log("News:: res.data:")
            console.log(res.data)
            console.log('project id >>>> ', res.data.project_id)
            this.checkNotifiedPopup()
            if(res.data.project_id){
              this.setState({
                loadPage: 1,
                last_page: 1,
                news_head: [{
                  title: t('loading_news'),
                  content: t('loading_news'),
                  date: t('loading_news'),
                  is_new: false
                }],
                new_all: [{
                  title: t('loading_news'),
                  content: t('loading_news'),
                  date: t('loading_news'),
                  is_new: false
                }],
              },async () => {
                await this.getAllNewsByProject(res.data.project_id)
              })
            }else {
              await this.getAllNewsList()
            }

            this.setState({
              noti_count: res.data.count_noti,
              user_point: res.data.point_balance,
              user_project_id: res.data.project_id,
              isBilling: res.data.user.enable_billing == null ? false : res.data.user.enable_billing,
              isMeter: res.data.user.enable_meter == null ? false : res.data.user.enable_meter,
              isShipping: res.data.user.enable_shipping == null ? false : res.data.user.enable_shipping,
              fb_is_link: res.data.user.fb_is_link,
              email: res.data.user.email,
            }, () => {
              if (res.data.message != null) {
                Alert.alert('แจ้งเตือนจากระบบ', res.data.message)
              }
            })
          } else {
           // this.setState({
              // isLoading: false
            // }, () => {
              clearToken();

              setTimeout(() => {
                this.props.appCleanUser();
                this.props.appCleanToken();
                this.props.appCleanProjectID();

                this.initData()
              }, 500)
            // })
          }
        })
    }else {
      await this.getAllNewsList()
    }
    return true
  }

  async getAllNewsByProject(project_id) {
    return getNewsByProject(project_id)
      .then(res => {
        console.log('res >>>>>>> ', res)
        this.setNewsData(res)
      })
  }

  async getAllNewsList () {
    // return getNews()
    return getNewsPage(this.state.loadPage)
      .then(res => {
        this.setNewsData(res)
      })
  }

  setNewsData(res) {
    if (res.data.data && (res.data.data).length > 5) {
      console.log('data  >>>>> ', res)
      var cut = []
      for (let index = 0; index < 5; index++) {
        cut.push(res.data.data[index])
      }

      this.setState({
        user: this.props.user,
        news_head: cut,
        new_all: res.data.data,
        refreshing: false,
        isLoading: false,
        last_page: res.data.last_page
      })
    } else {
      this.setState({
        news_head: res.data.data,
        new_all: res.data.data,
        refreshing: false,
        isLoading: false,
        last_page: res.data.last_page
      })
    }
  }

  initData () {
    console.log('initData >>> ')
    this.setState({
      isLoading: true,
    }, () => {
      Promise.all([
        this.getUser(),
        // this.getAllNewsList()
      ])
        .then(() => {
          let user_id = 0
          let user_noti_id = 0
          if (this.props.token != null) {
            if (this.state.isFirstTime) {
              this.props.appSetNotification(this.state.noti_count)
              this.props.appSetProjectID(this.state.user_project_id)
              this.setState({ isFirstTime: false })
            }
          }

          if (this.props.user && this.props.user.id) {
            user_id = 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 (this.props.token != null && this.props.user != null) {
            this.setState({
              auth: true,
            })
          } else {
            this.setState({
              auth: false
            })
          }

          this.setState({ isLoading: false })
        })
        .catch(() => {
          // console.log('catch ------------------>');
          // this.setState({isLoading:false})
          // this.props.appCleanUser()
          // this.props.appCleanToken()

          setTimeout(() => {
            this.setState({
              isLoading: false
            }, () => {
              //this.props.appCleanUser()
              //this.props.appCleanToken()
            })
          }, 600)
          // this.initData()
        })
    })
  }

  setPermission = async () => {
    try {
      const enabled = await messaging().hasPermission()
      if (!enabled) {
        await messaging().requestPermission()
      }
    } catch (error) {
      console.log('error', error)
    }
  }

  initNotification = async () => {
    await this.setPermission()
    const fcmToken = await messaging().getAPNSToken()
    if (fcmToken) {
      store.dispatch(appSetPushToken(fcmToken))
      const resultSendDevice = await registerDevice(fcmToken)
      console.log(' re sult register_device =>', resultSendDevice)
      if (resultSendDevice.ok && resultSendDevice.data.success) {
        store.dispatch(appSetDevice(resultSendDevice.data.device))
      }
    }

  }

  _onRefresh = () => {
    this.setState({
      refreshing: true, loadPage: 1, loadMore: false
    }, () => {
      this.initData()
      this.initNotification()
      // this.checkNotifiedPopup()
    })
  }

  setPaymentLater = () => {
    // setPaymentLater()
    //   .then(res => {
    //     if(res && res.data && res.data.success){
          this.setState({
            visibleNotiElectric: false,
            visibleNotiOverDue: false
          })

          if(this.state.is_notified_meter === true){
              this.setState({
                visibleNotiMeter: true
              }, () => {
                setTimeout(() => {
                  this.forceUpdate()
                }, 100)
              })
          }
        // }
      // })
  }

  setFillInMeterLater = () => {
    // setFillInMeterLater()
    //   .then(res => {
    //     if(res && res.data && res.data.success){
          this.setState({
            visibleNotiMeter: false
          })
        // }
      // })
  }

  renderNativeItem = ({ item }) => (
    <TouchableOpacity style={{ padding: 8, backgroundColor: '#FFFFFF33', height: 85, borderWidth: 1, borderColor: 'white', borderRadius: 5, flexDirection: 'row' }}
                      onPress={() => {this.props.navigation.navigate('NewsDetail', { news_id: item.id })}}>
      <Image source={item.url ? { uri: item.url } : require('../../../assets/images/default_small.png')} defaultSource={require('../../../assets/images/default_small.png')} style={styles.image_style} resizeMode={'contain'}/>
      <View style={{ flex: 1, marginLeft: 8, justifyContent: 'space-between' }}>
        <Text style={{ fontSize: 14, color: 'white', width: '100%', }} ellipsizeMode={'tail'} numberOfLines={2}>{item.title}</Text>
        <View style={{ flexDirection: 'row' }}>
          <Icon name="ic_calendar_alt" size={16} color="white"/>
          <Text style={{ flex: 1, fontSize: 12, color: 'white', marginLeft: 5 }}>{parseDateLocale(item.date)}</Text>
          {
            item.is_new == true  &&
              <View style={{ backgroundColor: '#FF9500', height: 20, paddingHorizontal: 10, borderRadius: 10, justifyContent: 'center', alignItems: 'center' }}>
                <Text style={{ fontSize: 12, color: 'white' }}>{item.type == "promotion" ? t('latest_promotion') : t('latest_news')}</Text>
              </View>
          }
        </View>
      </View>
    </TouchableOpacity>
  )

  renderNativeItemImages = (item) => {
    return <TouchableOpacity onPress={() => {
      this.props.navigation.navigate('NewsDetail', { news_id: item.id })
    }}>
      <ImageBackground source={item.url ? { uri: item.url } : require('../../../assets/images/default_big.png')} onError={(e) => { this.props.source = require('../../../assets/images/default_big.png') }} style={styles.imgBg}>
        <LinearGradient colors={['rgba(0, 0, 0, 0)', '#000000']}>
          <View style={{ padding: 15, }}>
            {item.is_new == true  ?
                <View style={{ backgroundColor: '#FF9500', borderRadius: 10, height: 23,
                alignSelf: 'flex-start', alignItems: 'center', justifyContent: 'center', flexWrap: 'nowrap',
                  paddingHorizontal: 10 }}>
                  <Text style={{ fontSize: 12, width: '100%', justifyContent: 'center', alignItems: 'center', color: 'white', flexWrap: 'nowrap' }}>{item.type == "promotion" ? t('latest_promotion') : t('latest_news')} </Text>
                </View>
                : null }
            <Text style={styles.textNewsName} ellipsizeMode={'tail'} numberOfLines={2}>{item.title}</Text>
            <View style={{ flexDirection: 'row', marginTop: 5 }}>
              <Icon name="ic_calendar_alt" size={14} color="rgba(255, 255, 255, 0.65)"/>
              <Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 12, marginLeft: 5, marginTop: -1 }}>
                {parseDateLocale(item.date)}
              </Text>
            </View>
          </View>
        </LinearGradient>
      </ImageBackground>
    </TouchableOpacity>
  }

  _onCarouselScroll (e) {
    const scrollX = e.nativeEvent.contentOffset.x
    this.setState({
      position: Math.ceil(scrollX / width)
    })
    // console.log(this.state.position)
  }

  isCloseToBottom = ({ layoutMeasurement, contentOffset, contentSize }) => {
    const paddingToBottom = 20
    return layoutMeasurement.height + contentOffset.y >=
      contentSize.height - paddingToBottom
  }

  loadMoreData = async () => {
    if(parseInt(this.state.loadPage) < parseInt(this.state.last_page)){
      this.setState({
        loadMore: true,
        isLoadmore: true,
        loadPage: this.state.loadPage + 1
      }, () => {
        getNewsPage(this.state.loadPage)
          .then(res => {
            if (res.ok) {
              let resData = res.data.data
              let news_all = this.state.new_all
              let news_arr = news_all.concat(resData)

              this.setState({
                new_all: news_arr,
                refreshing: false,
                loadMore: false,
                isLoadmore: false,
                last_page: res.data.last_page
              })
            }
          })
      })
    }

    /*loading - set loadMore = false when done*/
  }

  _keyExtractorNewHead = (item, index) => 'new_head_' + index
  _keyExtractorNewAll = (item, index) => 'new_all_' + index

  render () {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <NavigationEvents
          onDidFocus={() => {
            this.setState({
              isLoading: true
            }, () => {
              this.initData()
            })
          }}
        />
        <BackgroundImage>
          <ScrollView contentContainerStyle={styles.contentContainer}
                      refreshControl={
                        <RefreshControl
                          refreshing={this.state.refreshing}
                          onRefresh={this._onRefresh}
                        />
                      }
                      showsVerticalScrollIndicator={false}
                      scrollEventThrottle={16}
                      onScroll={Animated.event(
                        [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
                        {useNativeDriver: false}
                      )}
                      onMomentumScrollEnd={({ nativeEvent }) => {
                        if (this.isCloseToBottom(nativeEvent)) {
                          this.loadMoreData()
                        }
                      }}
          >
            <View style={[styles.row]}>
              <FlatList
                data={this.state.news_head}
                renderItem={({ item }) => this.renderNativeItemImages(item)}
                horizontal={true}
                showsHorizontalScrollIndicator={false}
                pagingEnabled={true}
                keyExtractor={this._keyExtractorNewHead}
                onScroll={this._onCarouselScroll}
              />
              <View style={{ position: 'absolute', bottom: 10, width: '100%', justifyContent: 'center', flexDirection: 'row' }}>
                {
                  this.state.news_head ?
                    (this.state.news_head).map((item, i) => <View key={'news_heade_' + i} style={[{ width: 10, height: 10, borderRadius: 5, backgroundColor: this.state.position == i ? '#269A21' : 'rgba(255,255,255,0.3)', marginHorizontal: 4 }]}></View>)
                    : <View></View>
                }
              </View>
            </View>

            {
              this.state.auth !== null &&
              (
                !this.state.auth ? (
                  <Card style={{ borderRadius: 5, backgroundColor: '#00420A', borderColor: 'rbga(0,0,0,0)', paddingBottom: 10 }}>
                    <BackgroundImage_RegisterForm>
                      <View style={{ flex: 1, alignItems: 'center', padding: 10 }}>
                        <View>
                          <Text style={{ color: 'white', fontSize: 16, textAlign: 'center' }}>{t('for_csa_customer')}</Text>
                          <Text style={{ color: 'white', fontSize: 16, textAlign: 'center' }}>{t('login')} {t('to_view_outstanding_balance')}</Text>
                        </View>
                        {/*<TouchableOpacity onPress={() => {
                          // this.props.navigation.navigate('Register')
                          this.props.navigation.navigate('Terms')
                        }}>
                          <View>
                            <Badge style={{ backgroundColor: '#145EB3', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', marginTop: 10, height: null, width: 150 }}>
                              <Text style={{ fontSize: 16, color: 'white', padding: 5, textAlign: 'center' }}>{t('create_account')}</Text>
                            </Badge>
                          </View>
                        </TouchableOpacity>*/}
                        {/* <Text style={{ color: 'white', marginTop: 10 }}>{t('or')}</Text> */}
                        <TouchableOpacity onPress={() => { this.props.navigation.navigate('Login') }}>
                          <View>
                            <Badge style={{ backgroundColor: '#145EB3', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', marginTop: 10, height: null, width: 150 }}>
                              <Text style={{ fontSize: 16, color: 'white', padding: 5, textAlign: 'center' }}>{t('login')}</Text>
                            </Badge>
                          </View>
                        </TouchableOpacity>
                        {/* {Platform.OS == 'ios' ? <Text style={{ color: 'white', marginTop: 10 }}>{t('or')}</Text> : null}
                        {Platform.OS == 'ios' ? <View>
                            <AppleButton
                             buttonStyle={AppleButton.Style.WHITE}
                             buttonType={AppleButton.Type.SIGN_IN}
                             style={{
                               width: 150,
                               height: 45,
                               marginTop: 10,
                             }}
                             onPress={ () => {signinApple(() => {
                                 this.initData()
                               })
                             }}
                           />
                         </View> : null}

                        <Text style={{ color: 'white', marginTop: 10 }}>{t('or')}</Text>

                          <TouchableOpacity onPress={() => {
                            loginWithFacebook(() => {
                              this.initData()
                            })}}>


                          <View>
                            <Badge style={{ backgroundColor: '#145EB3', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', marginTop: 10, height: null, width: 150 }}>
                              <Text style={{ fontSize: 16, color: 'white', padding: 5, textAlign: 'center' }}>{t('login_facebook')}</Text>
                            </Badge>
                          </View>
                        </TouchableOpacity> */}
                      </View>
                    </BackgroundImage_RegisterForm>
                  </Card>
                ) : (
                  <View style={{ padding: 5 }}>
                    <View style={[styles.row, { alignItems: 'stretch' }]}>
                      <View style={styles.custom_card}>
                        <Card style={{ borderRadius: 5, backgroundColor: '#00420A', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                          <BackgroundImage_RegisterForm>
                            <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 10, minHeight: 177 }}>
                              <View style={{ justifyContent: 'center', alignItems: 'center' }}>
                                <Icon name='ic_shop_receive' color='white' size={24}/>
                                {/*<Text style={{ color: 'white', fontSize: 14, marginTop:5 }}>คุณมียอดค้างชำระ</Text>*/}
                                <Text style={{ color: 'white', fontSize: 14, marginTop: 5, textAlign: 'center' }}> {t('have_outstanding_balance')} </Text>
                              </View>
                              <View style={{ justifyContent: 'center', alignItems: 'center', marginBottom: 5 }}>
                                <Text style={{ color: 'white', fontSize: 28 }}>{this.state.isBilling ? this.state.pending_payment : 'N/A'}</Text>
                                {/*<Text style={{ color: 'white', fontSize: 12 }}>{parseFloat(this.state.pending_payment) > 0 ?'โปรดชำระก่อนวันที่':'ยังไม่มียอดค้างชำระ'}</Text>*/}
                                <Text style={{ color: 'white', fontSize: 12, textAlign: 'center' }}>{parseFloat(this.state.pending_payment) > 0 ? t('to_view_outstanding_balance') : t('no_outstanding_balance_yet')}</Text>
                                {this.state.due_at !== '' && <Text style={{ color: 'white', fontSize: 12 }}>{parseFloat(this.state.pending_payment) > 0 && this.state.due_at !== '' ? this.state.due_at : ''} </Text>}
                              </View>
                              <TouchableOpacity disabled={!this.state.isBilling} onPress={() => {this.props.navigation.navigate('Bill')}}>
                                {/*<Badge style={{ backgroundColor: this.state.isBilling ? '#145EB3' : 'gray', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', justifyContent:'center' }}><Text style={{ fontSize: 12, color: 'white' }}>ดูเพิ่มเติม</Text></Badge>*/}
                                <Badge style={{ backgroundColor: this.state.isBilling ? '#145EB3' : 'gray', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', justifyContent: 'center' }}><Text style={{ fontSize: 12, color: 'white' }}>{t('view_more')}</Text></Badge>
                              </TouchableOpacity>
                            </View>
                          </BackgroundImage_RegisterForm>
                        </Card>
                      </View>
                      <View style={[styles.custom_card]}>
                        <Card title='' style={{ borderRadius: 5, backgroundColor: '#003114', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                          <BackgroundImage_RegisterForm>
                            <View style={{
                              flex: 1,
                              flexDirection: 'column',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              padding: 10,
                              minHeight: 177,
                            }}>
                              <Icon name='ic_star' color='white' size={24}/>
                              <Text style={{ color: 'white', fontSize: 14, marginTop: 5 }}>{t('view_points')}</Text>
                              <Text style={{ color: 'white', fontSize: 28 }}>{parseFloat(this.state.user_point).toLocaleString()}</Text>
                              {/*<Text style={{ color: 'white', fontSize: 18 }}>พอยต์</Text>*/}
                              <Text style={{ color: 'white', fontSize: 14 }}>{t('point')}</Text>
                              <TouchableOpacity style={{ marginTop: 5 }}
                                                onPress={() => {this.props.navigation.navigate('Redeem')}}>
                                <Badge style={{ backgroundColor: '#145EB3', borderRadius: 5, borderColor: 'rbga(0,0,0,0)', justifyContent: 'center' }}>
                                  <Text style={{ fontSize: 12, color: 'white' }}>{t('redeem')}</Text>
                                </Badge>
                              </TouchableOpacity>
                            </View>
                          </BackgroundImage_RegisterForm>
                        </Card>
                      </View>
                    </View>
                    <View style={[styles.row, { flexWrap: 'wrap', alignItems: 'stretch' }]}>
                      <View style={[styles.custom_card]}>
                        <TouchableOpacity disabled={false} onPress={() => {
                          this.props.navigation.navigate('Meter')
                        }} style={{ flex: 1 }}>
                          <Card title='' style={{ borderRadius: 5, backgroundColor: '#145EB3', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                            <View style={{
                              flex: 1,
                              flexDirection: 'column',
                              alignItems: 'center',
                              padding: 10,
                              justifyContent: 'center'
                            }}>
                              <View style={{ alignItems: 'center' }}>
                                <Icon name='ic_meter' color='white' size={24}/>
                                <Text style={{ color: 'white', fontSize: 14, textAlign: 'center', marginTop: 5 }}> {t('smart_meter')} </Text>
                              </View>
                            </View>
                          </Card>
                        </TouchableOpacity>
                      </View>
                      <View style={[styles.custom_card]}>
                        <TouchableOpacity disabled={false} onPress={() => {
                          this.props.navigation.navigate('Object',{
                            user:this.props.user
                          })
                        }} style={{ flex: 1 }}>
                          <Card title='' style={{ borderRadius: 5, backgroundColor: '#145EB3', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                            <View style={{
                              flex: 1,
                              flexDirection: 'column',
                              alignItems: 'center',
                              padding: 10,
                              justifyContent: 'center'
                            }}>
                              <View style={{ alignItems: 'center' }}>
                                <Icon name='ic_cart' color='white' size={24}/>
                                <Text style={{ color: 'white', fontSize: 14, textAlign: 'center', marginTop: 5 }}>{t('mail_and_parcel')}</Text>
                              </View>
                            </View>
                          </Card>
                        </TouchableOpacity>
                      </View>
                      <View style={[styles.custom_card]}>
                        <TouchableOpacity disabled={false}
                          /*onPress={() => { this.props.navigation.navigate('RepairService',{
                            user:this.props.user
                          }) }}*/
                          onPress={() => { this.props.navigation.navigate('Repair')}}
                          style={{ flex: 1 }}>
                          <Card title='' style={{ borderRadius: 5, backgroundColor: '#145EB3', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                            <View style={{
                              flex: 1,
                              flexDirection: 'column',
                              alignItems: 'center',
                              padding: 10,
                              justifyContent: 'center',
                            }}>
                              <View style={{ alignItems: 'center' }}>
                                <Icon name='icon_repair' color='white' size={24}/>
                                <Text style={{ color: 'white', fontSize: 14, textAlign: 'center', marginTop: 5 }}>{t('request_repair')}</Text>
                              </View>
                            </View>
                          </Card>
                        </TouchableOpacity>
                      </View>
                      <View style={[styles.custom_card]}>
                        <TouchableOpacity disabled={false} onPress={() => {this.props.navigation.navigate('Question')}} style={{ flex: 1 }}>
                          <Card title='' style={{ borderRadius: 5, backgroundColor: '#145EB3', borderColor: 'rbga(0,0,0,0)', flex: 1 }}>
                            <View style={{
                              flex: 1,
                              flexDirection: 'column',
                              alignItems: 'center',
                              padding: 10,
                              justifyContent: 'center',
                            }}>
                              <View style={{ alignItems: 'center' }}>
                                <Icon name='ic_qa' color='white' size={24}/>
                                <Text style={{ color: 'white', fontSize: 14, textAlign: 'center', marginTop: 5 }}>{t('inquire')}</Text>
                              </View>
                            </View>
                          </Card>
                        </TouchableOpacity>
                      </View>
                    </View>
                  </View>
                ))

            }

              <View style={{ padding: 10 }}>
                <FlatList
                  extraData={this.state}
                  contentContainerStyle={{
                    height: '100%',
                    width: '100%'
                  }}
                  // scrollEnabled={false}
                  data={this.state.new_all}
                  renderItem={this.renderNativeItem}
                  keyExtractor={this._keyExtractorNewAll}
                  // onEndReachedThreshold={0.01}
                  // onEndReached={this.loadMoreData.bind(this)}
                  ItemSeparatorComponent={() => {
                    return <View style={{ width: '100%', height: 8 }}></View>
                  }}
                  ListFooterComponent={() => {
                    if (!this.state.isLoadmore) return null
                    return (<ActivityIndicator
                      size="large"
                      color={'white'}
                    />)
                  }}
                />
              </View>
          </ScrollView>
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
        <PopupNotiElectric
          isVisible={this.state.visibleNotiElectric}
           onCancel={() => this.setState({visibleNotiElectric: false})}
           onPressLater={() => this.setPaymentLater()}
            pending_payment={this.state.pending_payment}
          due_at_payment={this.state.due_at_payment}
           onPress={() => this.setState({
             visibleNotiElectric: false
           }, () => {
             this.props.navigation.navigate('Bill')
             this.setPaymentLater()
           })}/>
        <PopupOverDue
          isVisible={this.state.visibleNotiOverDue}
           onCancel={() => this.setState({visibleNotiOverDue: false})}
          onPressLater={() => this.setPaymentLater()}
          pending_payment={this.state.pending_payment}
           onPress={() => this.setState({
             visibleNotiOverDue: false
           }, () => {
             // this.props.navigation.navigate('Payment', {payment_id: this.state.payment_id})
             this.props.navigation.navigate('Bill')
             this.setPaymentLater()
           })}/>
         <PopupNotiFillInMeter
           isVisible={this.state.visibleNotiMeter}
           onCancel={() => this.setState({visibleNotiMeter: false})}
           onPressLater={() => this.setFillInMeterLater()}
           notified_meter_at={this.state.notified_meter_at}
           onPress={() => this.setState({
             visibleNotiMeter: false
           }, () => {
             this.props.navigation.navigate('Meter')
             this.setFillInMeterLater()
           })}
         />
      </LinearGradient>
    )
  }
}

//export default NewsScreen

const styles = StyleSheet.create({
  container: {
    flex: 1, flexDirection: 'column',
    padding: 7
  },
  row: {
    flex: 1, flexDirection: 'row',
  },
  textNews: {
    backgroundColor: '#0D8890',
    width: 60,
    color: '#FFFFFF',
    borderRadius: 5,

    textAlign: 'center',
    fontSize: 12
  },
  imgBg: {
    flex: 1,
    height: 200,
    width: width,
    justifyContent: 'flex-end'
  },
  textNewsName: {
    color: '#FFFFFF',
    fontSize: 18
  },
  textDate: {
    color: 'white',
    fontSize: 12,
    marginLeft: 5,
    marginTop: 10
  },
  contentContainer: {
    paddingVertical: 0,
  },
  image_style: {
    height: 64,
    width: 64,
    borderRadius: 5,
  },
  custom_card: {
    width: '50%', paddingHorizontal: 5,
    // width: '100%'
  },
  popupNoti: {
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 5,
    marginHorizontal: 50,
    paddingVertical: 20,
    paddingHorizontal: 30,
    maxWidth: 300,
    width: '100%'
  },
  popupNotiContainer: {
    backgroundColor: 'rgba(0,0,0,0.6)',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    width: '100%',
    height: '100%',
    flex: 1
  },
  costText: {
    backgroundColor: '#EFEFF4',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 5,
    borderRadius: 5,
    width: '100%',
    marginBottom: 10
  },
  badgeCancel: {
    backgroundColor: 'white',
    alignItems: 'center',
    width: '100%'
  },
  badgeSubmit: {
    backgroundColor: '#145EB3',
    borderRadius: 5,
    marginBottom: 10,
    alignItems: 'center',
    width: '100%',
    height: 'auto'
  },
  TextFont: {
    fontFamily: 'Prompt-Regular',
  }
})

const mapDisPatchToProps = state => {
  return state.app
}

const setUser = dispatch => bindActionCreators({
  appSetToken,
  appSetPushToken,
  appSetDevice,
  appSetUser,
  appCleanToken,
  appCleanUser,
  appSetNotification,
  appSetProjectID,
  setPaymentLater,
  appCleanProjectID
}, dispatch)
export default connect(mapDisPatchToProps, setUser)(NewsScreen)
