import React, { Component } from 'react'
import IconAntDesign from 'react-native-vector-icons/AntDesign'
import Icon from '../../components/Icon'
import {
  Accordion,
  Badge,
  Body,
  Button,
  Content,
  Header,
  Left,
  List,
  ListItem,
  Right,
  Title,
  View
} from 'native-base'
import { Dimensions, FlatList, ScrollView, StyleSheet, TouchableOpacity, SafeAreaView, Alert } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import Text from '../../components/Text';
import { payment } from '../../api/UserApi'
import { connect } from "react-redux";
import {bindActionCreators} from "redux";
import {appSetDevice, appSetPushToken, appSetToken, appSetUser} from "../../redux/app/action";
import moment from "moment";
import IndicatorLoading from '../../components/IndicatorLoading';
import { t } from 'src/utils/i18n'
import parseDateLocale from 'src/utils/parseDateLocale';
import { NavigationEvents } from 'react-navigation'
const { height, width } = Dimensions.get('window')
import { CustomInput } from '../../components/CustomInput'
import debounce from 'lodash/debounce'

function ItemOrder({title,cost,description,type}){

  let iconShow = ''
  let iconColor = ''
  switch(type){
    case 0:
      iconShow = 'ic_event_note'
      iconColor = '#00000080'
      break;
    case 1:
      iconShow = 'ic_bed'
      iconColor = '#FF6122'
      break;
    case 2:
      iconShow = 'ic_water'
      iconColor = '#5AC8FA'
      break;
    case 3:
      iconShow = 'ic_thunder'
      iconColor = '#FFCC00'
      break;
    case 4:
      iconShow = 'ic_event_note'
      iconColor = '#00000080'
      break;
    case 5:
      iconShow = 'ic_water'
      iconColor = '#5AC8FA'
      break;
    case 6:
      iconShow = 'ic_thunder'
      iconColor = '#FFCC00'
      break;
    case 7:
      iconShow = 'ic_event_note'
      iconColor = '#00000080'
      break;
  }

  return <View style={{flexDirection:'row',height:64,width:'100%',borderBottomWidth:1,alignItems:'center',borderColor:'#EAEAF4',paddingHorizontal:16}}>
    <View style={{ ...styles.circleShapeView, backgroundColor: iconColor,marginRight:16 }}>
      <Icon active name={iconShow} size={20} color="white" />
    </View>
    <View style={{flex:1}}>
      <View style={{ flexDirection: 'row' }}>
        <Text style={{ flex: 1 }}>{title}</Text>
        <Text style={{ ...styles.colorTextPayment, textAlign: 'center' }}>{cost} {t('baht')}</Text>
      </View>
      <Text style={{ color: '#00000080', fontSize: 12, marginLeft: 5}}>{description != '' ? description : '-'}</Text>
    </View>
  </View>
}

class BillScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading:false,
      payment: [],
      sum_payment: [],
      activePage: 0,
      isCanPay: true,
      all_payment : [],
      room_number_array : [],
      page: 1,
      total_page: 1,
      currentIndex: 0,
      search: ''
    };

    this._onCarouselScroll = this._onCarouselScroll.bind(this)
    this.checkDueDate = this.checkDueDate.bind(this)
    this.checkstatusBill = this.checkstatusBill.bind(this)
    this.debounceSearch = debounce(() => {
      this.setState({
        page: 1,
        all_payment : [],
        room_number_array : [],
        payment: [],
        sum_payment: [],
        total_page: 1,
        currentIndex: 0
      }, () => {
        this.getPaymentPagination()
      })
    }, 2500)
  }

  componentDidMount() {
    if(this.props.user){
        this.getPaymentPagination()
    }
  }

  getPaymentPagination () {
    this.setState({
       isLoading: true
    }, () => {
      payment(this.props.user.id, this.state.page, this.state.search)
        .then(res => {
          if(res.ok){
            let sum_payment = [];
            let array_payment = [];
            let sum_cost_room = res.data.sum_cost_room;
            if(Object.keys(sum_cost_room).length > 0) {
              Object.keys(sum_cost_room).map((sum_cost) => {
                sum_payment.push({
                    total_cost : sum_cost_room[sum_cost].total_cost,
                    room: sum_cost_room[sum_cost].room,
                    project: sum_cost_room[sum_cost].project,
                    due_at: sum_cost_room[sum_cost].due_at,
                  }
                )
              })
            }

            sum_payment = this.state.sum_payment.concat(sum_payment)
            let payment = res.data.payment_room_period
            if(Object.keys(payment).length > 0){
              this.setState({
                room_number_array: Object.keys(payment).sort()
              })

              Object.keys(payment).map((pay) => {
                if(Object.keys(payment[pay]).length > 0){
                  Object.keys(payment[pay]).map((detail) => {
                    array_payment.push({
                      room_id: pay,
                      period: detail,
                      ...payment[pay][detail]
                    })
                  })
                }
              })
            }

            let all_payment_data = this.state.all_payment.concat(array_payment)

            let array_room_no = this.state.room_number_array;
            this.setState({
              room_number_array: array_room_no.filter((item, i, ar) => ar.indexOf(item) === i)
            });


            let first_room = this.state.room_number_array[0];
            array_payment = array_payment.filter((obj)=>{
              return Object.keys(obj).reduce((acc, curr)=>{
                return obj.room_id === first_room
              }, false);
            });

            let date_now = moment()
            let findTimeout = array_payment.find((item) => {
              console.log('item >>> ',item)
              return moment(item.due_at) == date_now
            })
            //check bill timeout
            if(findTimeout !== undefined){
              this.setState({
                isCanPay: false
              })
            }


            if(sum_payment.length > 0){
                this.setState({
                  room_number_array: sum_payment.map(function(item){
                      return item.room
                  })
                });
            }

            this.setState({
              isLoading:false,
              payment: array_payment,
              sum_payment: sum_payment,
              all_payment: all_payment_data,
              page: res.data.page,
              total_page: res.data.total_page
            }, () => {
              this.roomFilter(this.state.currentIndex)
            } )
          }else {
            this.setState({
              isLoading: false
            })
          }
        })
    })
  }

  getTitle (period) {
    let period_month = moment(period, "MM/Y").format('MMMM');
    let period_year = parseInt(moment(period, "MM/Y").locale('en').format('Y'));
    let new_month = '';
    let new_period = period_month + ' ' + period_year;
    return new_period;
  }

  checkDueDate(date){
    // console.log('date -------- ',moment(date))
    // console.log('now -------- ',moment())
    let due_date = moment(date)
    let now = moment()
    if(due_date < now){
      return false
    }
    return true
  }

  checkstatusBill(data, isOverdue){
    if(data.status == 'paid'){
      return <TouchableOpacity style={{backgroundColor:data.status === 'pending' ? '#145EB3' : 'white',
            height: 32,width: 103,justifyContent:'center',alignItems:'center',borderRadius:5,
            borderColor: data.status !== 'pending' ? 'grey' : '',
            borderWidth: data.status !== 'pending' ? 1 : 0}}
            disabled={data.status === 'pending' ? false : true}
            onPress={() => {
              this.state.isCanPay ?
              data.status === 'pending' && this.props.navigation.navigate('PaymentDetail',{payment_id:data.payment_id})
              : Alert.alert(null, t('payment_overdue_contact_admin'),[{text: t('ok')}])
              }}>
        <Text style={{ color: data.status === 'pending' ? 'white' : 'rgba(0, 0, 0, 0.25)'}}>{data.status === 'pending' ? t('view_more') : t('paid1')}</Text>
      </TouchableOpacity>
    }else{
      if(isOverdue){
        return <View>
          <Text style={{ color: 'red',borderWidth:1,borderColor:'#00000040',borderRadius:5,paddingHorizontal:6}}>{t('overdue')}</Text>
        </View>
      }else{
        return <TouchableOpacity style={{backgroundColor:data.status === 'pending' ? '#145EB3' : 'white',
              height: 32,width: 103,justifyContent:'center',alignItems:'center',borderRadius:5,
              borderColor: data.status !== 'pending' ? 'grey' : '',
              borderWidth: data.status !== 'pending' ? 1 : 0}}
              disabled={data.status === 'pending' ? false : true}
              onPress={() => {
                this.state.isCanPay ?
                data.status === 'pending' && this.props.navigation.navigate('PaymentDetail',{payment_id:data.payment_id})
                : Alert.alert(null, t('payment_overdue_contact_admin'),[{text: t('ok')}])
                }}>
          <Text style={{ color: data.status === 'pending' ? 'white' : 'rgba(0, 0, 0, 0.25)'}}>{data.status === 'pending' ? t('view_more') : t('paid1')}</Text>
        </TouchableOpacity>
      }
    }
  }

  _renderHeader(data, expanded) {
    // if(data.room_id == this.state.sum_payment[this.state.activePage].room.id){
      let checkBool = this.checkDueDate(data.due_date == null || data.due_date == undefined ? moment() : data.due_date)
      return (
        <View style={{flex:1,flexDirection:'row',backgroundColor:'#B8DAAA',height: 64,borderBottomWidth:1,borderBottomColor:'white',alignItems:'center',justifyContent:'space-between',paddingHorizontal:16}}>
          <View style={{justifyContent:'center',flex:1}}>
            {/*<Text>{t('month')} {parseDateLocale(moment(data.period, 'MM/Y'), 'MMMM Y')}</Text>*/}
            <Text>{t('payment_no')} : {data.invoice_code}</Text>
            <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
              {
                data.status !== 'complete' && <Text note style={styles.colorTextPayment}>{t('outstanding_balance')} {data.total_cost}</Text>
              }
              {expanded || <Text style={{fontSize:10,marginRight:16}}>{t('view_more')}</Text>}
            </View>
          </View>
          {/*{
            this.checkstatusBill(data, data.is_overdue)
          }*/}

          <TouchableOpacity style={{
            backgroundColor: data.status === 'complete' ? 'lightgrey' : '#145EB3', 
            height: 32,width: 103,
            justifyContent:'center',
            alignItems:'center',
            borderRadius:5,
            borderColor: data.status === 'complete' ? 'grey' : '',
            borderWidth: data.status === 'complete' ? 1 : 0
          }}
                            onPress={ data.status === 'complete' ? () => {} : () => { this.props.navigation.navigate('PaymentDetail',{payment_id: data.id, room: data.room_id})}}
                            disabled={ data.status === 'complete'}
          >
            <Text style={{ color: 'white' }}>{data.status === 'complete' ? t('paid1') : t('view_more')}</Text>
          </TouchableOpacity>
         

          {/* {
            checkBool ?
            data.enable_qr &&
            <TouchableOpacity style={{backgroundColor:data.status === 'pending' ? '#145EB3' : 'white',
                  height: 32,width: 103,justifyContent:'center',alignItems:'center',borderRadius:5,
                  borderColor: data.status !== 'pending' ? 'grey' : '',
                  borderWidth: data.status !== 'pending' ? 1 : 0}}
                  disabled={data.status === 'pending' ? false : true}
                  onPress={() => {
                    this.state.isCanPay ?
                    data.status === 'pending' && this.props.navigation.navigate('Payment',{payment_id:data.id})
                    : Alert.alert(null, 'รายการค้างชำระของคุณ เกินกำหนดชำระ กรุณาติดต่อสำนักงานบริการลูกค้า',[{text: t('ok')}])
                    }}>
              <Text style={{ color: data.status === 'pending' ? 'white' : 'rgba(0, 0, 0, 0.25)'}}>{data.status === 'pending' ? 'จ่ายเงิน' : 'จ่ายแล้ว'}</Text>
            </TouchableOpacity>
            :
            <View>
              <Text style={{ color: 'red',borderWidth:1,borderColor:'#00000040',borderRadius:5,paddingHorizontal:6}}>{'เกินกำหนดชำระ'}</Text>
            </View>
          } */}
        </View>
      )
    // }
  }

  _renderContent(data) {
    // let water_cost = 0;
    // let electrict_cost = 0;
    // let room_cost = 0;
    // let service_cost = 0;
    // let date_payment = '';
    // let extra_info = '';
    // let d = moment(data.created_at).format('D')
    // let m = moment(data.created_at).format('MM')
    // let y = parseInt(moment(data.created_at).format('Y')) + 543
    //date_payment = d + ' ' + this.getMonth(m) + ' ' + y

    // let descriptionRoom = '-'
    // let descriptionWater = '-'
    // let descriptionElec = '-'
    // let descriptionService = '-'

    // console.log('check data ----------> ',data)

    // if(data.details){
    //   data.details.map((det) => {
    //     if(det.sequence === 1){
    //       room_cost = det.cost
    //       room_extra_info = det.extra_info != null ? det.extra_info : ''
    //       descriptionRoom = det.descript == '' ? '-' : det.descript
    //     }

    //     if(det.sequence === 2){
    //       water_cost = det.cost
    //       water_extra_info = det.extra_info != null ? det.extra_info : ''
    //       descriptionWater = det.descript == '' ? '-' : det.descript
    //     }

    //     if(det.sequence === 3){
    //       electrict_cost = det.cost
    //       electrict_extra_info = det.extra_info != null ? det.extra_info : ''
    //       descriptionElec = det.descript == '' ? '-' : det.descript
    //     }

    //     if(det.sequence === 4){
    //       service_cost = det.cost
    //       service_extra_info = det.extra_info != null ? det.extra_info : ''
    //       descriptionService = det.descript == '' ? '-' : det.descript
    //     }
    //   })
    // }

    return (
      <View>
        {
          data.details.map((info,index) => {
            return <ItemOrder title={info.name} cost={info.cost} description={info.descript} key={'order_info_'+index} type={info.type}/>
          })
        }
        <View style={{ height:50,width:'100%', backgroundColor:'#8BC34A',alignItems: 'flex-end',justifyContent:'center' }}>
          <Text style={{ color: 'white',marginRight:15,fontSize:18 }}>{t('total')} {data.total_cost} {t('baht')}</Text>
        </View>
      </View>
    )
  }

  handlePrevious = () => {
    let currentIndex = this.state.currentIndex - 1;
    
    this.setState({
      currentIndex,
      activePage: currentIndex
    }, () => {
      this.roomFilter(this.state.currentIndex)
      this.flatListRef.scrollToIndex({index: this.state.currentIndex, animated: true})
    })
  }

  handleNext = () => {
    let currentIndex = this.state.currentIndex;
    let dataLength = this.state.sum_payment.length
    if(dataLength > this.state.currentIndex) {
      currentIndex += 1;
      this.roomFilter(currentIndex)
      this.setState({
        currentIndex,
        activePage: currentIndex
      }, () => {
        this.flatListRef.scrollToIndex({index: currentIndex, animated: true})
        if(dataLength - 1 == this.state.currentIndex && this.state.page < this.state.total_page) {
          this.setState({
            page: parseInt(this.state.page) + 1
          }, () => {
            this.getPaymentPagination()
          })
        }
      })
    }
  }

  renderNativeItemImages = (item) => {
    // console.log('check data item ',item)
    return <View style={{display: 'flex', flexDirection: 'row', alignItems: 'center', position: 'relative'}}>
      {
        this.state.currentIndex > 0 && 
        <TouchableOpacity onPress={this.handlePrevious} style={{position: 'absolute', left: 5, zIndex: 1}}>
          <IconAntDesign name="left" size={35} color={'#0e5e29'}></IconAntDesign>
        </TouchableOpacity>
      }
        
        <View style={{width: width, alignItems: 'center', paddingTop: 10, paddingBottom: 40,height: 177, zIndex: 0}}>
          <View style={{width: '65%', height: '100%', backgroundColor: '#06ADB8', borderRadius: 5 }}>
            <LinearGradient colors={['#4BAF3B', '#0e5e29']} style={{ flex:1, borderRadius: 5, height: 120,paddingBottom:10, justifyContent:'space-between'}}>
              <View style={{ padding: 16,paddingBottom: 5,paddingTop:10 , borderRadius: 5}}>
                <Text style={{ color: 'white', fontSize: 18 }}>{t('room')} {item.room}</Text>
                <Text style={{ color: 'rgba(255, 255, 255, 0.65)', fontSize: 14 }}>{item.project && item.project.name}</Text>
                <Text style={{ color: 'white' }}>{t('outstanding_balance')} <Text style={{ color: 'white' ,fontSize:16 }}>{item.total_cost} {t('baht')}</Text></Text>
              </View>

              {
                item.due_at !== null
                    ? (
                        <View style={{backgroundColor: '#FF2D55',justifyContent:'center',alignItems:'center', paddingHorizontal: 5}}>
                          <Text style={{ fontSize: 12, color: 'white'}}>{t('please_pay_within')} {this.props.lang === 'th' ? moment(item.due_at).add(543, 'year').format('DD MMM YYYY') : moment(item.due_at).format('DD MMM YYYY')}</Text>
                        </View>
                    )
                    : null
              }

            </LinearGradient>
          </View>
        </View>
        
        {
          this.state.currentIndex < this.state.sum_payment.length - 1 &&
          <TouchableOpacity onPress={this.handleNext} style={{position: 'absolute', right: 5, zIndex: 1}}>
            <IconAntDesign name="right" size={35} color={'#0e5e29'}></IconAntDesign>
        </TouchableOpacity>
        }
      </View>
  }

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

  groupArrayOfObjects(list, key) {
    return list.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }

  roomFilter(index){
    let payment_exits = this.state.all_payment;
    let another_room = this.state.room_number_array[index];
    let payment_array = [];
    if(payment_exits && payment_exits.length > 0){
      payment_array = payment_exits.filter((payment) => {
        return payment.room_id === another_room;
      })
    }
    this.setState({ payment: payment_array })
  }

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

  handleSearch = (search) => {
    this.setState({
      search
    }, () => {
      this.debounceSearch()
    })
  }

  render() {
    return (
      <SafeAreaView style={{flex: 1}}>
        <ScrollView contentContainerStyle={styles.contentContainer}>
          <View style={{ alignItems: 'center'}}>
            <View>
              <CustomInput
                onChangeText={this.handleSearch}
                inputTextAlign={'left'}
                iconName={'ic_search'}
                placeholder={'Search Room'}
                placeholderTextColor={'#FFFFFF40'}
                value={this.state.search}
                style={styles.form_input} />
            </View>

            {
              this.state.sum_payment.length == 0 &&
                <View style={{margin:16,width: '90%', height: 55,backgroundColor:'#00000080',justifyContent:'center',alignItems:'center',borderRadius:5}}>
                  <Text style={{fontSize:14,color:'white',textAlign:'center'}}>{this.state.search === '' ? t('no_outstanding_balance') : t('room_not_found')}</Text>
                </View>
            }

            <FlatList
              data={this.state.sum_payment}
              renderItem={({ item }) => this.renderNativeItemImages(item)}
              horizontal={true}
              // onScroll={this._onCarouselScroll}
              // onScrollEndDrag={this.roomFilter(this.state.activePage)}
              // pagingEnabled={true}
              extraData={this.state}
              keyExtractor={this._keyExtractor}
              scrollEnabled={false}
              ref={(flatlist) => { this.flatListRef = flatlist }}
            />
            <View style={{ position: 'absolute', bottom: 10, width: '100%', justifyContent: 'center', flexDirection: 'row' }}>
              {this.state.sum_payment.map((item, i) => <View key={'sum_payment_'+i} style={[{ width: 10, height: 10, borderRadius: 5, backgroundColor: this.state.activePage == i ? '#269A21' : 'rgba(124, 187, 51, 0.3)', marginHorizontal: 4 }]}></View>)}
            </View>
          </View>
          <View style={{flex:1}}>
            <Accordion
                dataArray={ this.state.payment }
                expanded={this.state.payment && this.state.payment.length > 0 ? this.state.payment.length - 1 : []}
                renderHeader={(data, expanded) => { return this._renderHeader(data, expanded) }}
                renderContent={(data) => { return this._renderContent(data) }} />
          </View>
        </ScrollView>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </SafeAreaView>
    )
  }
}

const styles = StyleSheet.create({
  circleShapeView: {
    width: 32,
    height: 32,
    borderRadius: 100,
    justifyContent: 'center',
    alignItems: 'center'
  },
  contentContainer: {
    backgroundColor: '#EEFFD7',
    paddingVertical: 0,
    flexGrow: 1,
  },
  colorTextPayment: {
    color: '#3AA40C'
  },
  form_input: {
    backgroundColor: '#4BAF3B',
    borderColor: '#0e5e29',
    borderRadius: 30,
    borderWidth: 1,
    width: '80%',
    marginTop: 10
  },
})

const mapDisPatchToProps = state => ({
  user: state.app.user,
  lang: state.app.lang
})

export default connect(mapDisPatchToProps)(BillScreen)
