import React, {Component} from 'react'
import { View, StyleSheet, ImageBackground, Text, FlatList, TouchableOpacity, Modal, Alert, ScrollView } from 'react-native';
import FastImage from 'react-native-fast-image';
import { getListMyReward, payment_detail, useRentalDiscount, removeRentalDiscount } from '../../api/UserApi';
import IndicatorLoading from '../../components/IndicatorLoading';
import IconFontawesome from 'react-native-vector-icons/FontAwesome'
import IconMaterial from "react-native-vector-icons/MaterialCommunityIcons";
import { NavigationEvents } from 'react-navigation';
import { t } from '../../utils/i18n';

class PaymentDetail extends Component {
  constructor(props){
    super(props);
    this.state = {
      payment: null,
      coupon_list: [],
      modalVisible: false,
      isLoading: false,
      couponSelected: null,
      couponHighlight: null,
      payment_id: null,
      room: null
    }
  }

  componentDidMount(){
    const payment_id = this.props.navigation.getParam('payment_id', null);
    const room = this.props.navigation.getParam('room', null);

    this.setState({
      room
    })

    if(payment_id){
      this.setState({
        isLoading: true,
        payment_id
      })
    }
  }

  getPaymentDetail = () => {
    payment_detail(this.state.payment_id)
    .then(res => {
      if(res.data && res.data.success){
        this.setState({
          payment: res.data,
          isLoading: false
        }, () => {
          this.getCouponList()
        })
      }else {
        this.setState({
          isLoading: false
        })
      }
    })
  }

  getCouponList = () => {
    getListMyReward('', 1, this.state.payment.is_coupon ? this.state.payment_id : '')
      .then(res => {
        if(res.data && res.data.data){
          let coupon = null;
          if(res.data.data.length > 0 && this.state.payment && this.state.payment.coupon && this.state.payment.coupon.id){
            coupon = res.data.data.filter((item) => item.id === this.state.payment.coupon.id);
            if(coupon && coupon.length > 0){
              coupon = coupon[0]
            }
          }
          this.setState({
            coupon_list: res.data.data,
            isLoading: false,
            couponSelected: coupon
          })
        }else{
          this.setState({
            isLoading: false
          })
        }
      })
  }

  renderItem = (item) => {
    return (
      <View style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between', marginBottom: 8}}>
        <Text style={[styles.mainText, {color: 'black'}]}>{item.cost_name}</Text>
        <Text style={[styles.mainText, {color: '#7CBB33', fontWeight: '500'}]}>{parseFloat(item.total).toLocaleString()} {t('baht')}</Text>
      </View>
    )
  }

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

  visibleCoupon = () => {
    this.setState({
      modalVisible: true
    })
  }

  useCoupon = () => {
    this.setState({
      modalVisible: false,
      isLoading: true
    }, () => {
      useRentalDiscount(this.state.couponHighlight.id, this.state.payment_id)
      .then(res => {
        if(res.data && res.data.success){
          this.setState({
            couponSelected: this.state.couponHighlight,
            // isLoading: false,
            modalVisible: false,
            payment_id: res.data.new_payment_id,
          }, () => {
            setTimeout(() => {
              this.getPaymentDetail()
            }, 3000)
          })
        }else {
          let message = res.data && res.data.message ? res.data.message : t('failed_coupon')
          Alert.alert(message)
          this.setState({
            isLoading: false
          })
        }
      })

    })
  }

  removeCoupon = () => {
    this.setState({
      isLoading: true
    }, () => {
      removeRentalDiscount(this.state.couponSelected.id, this.state.payment_id)
        .then(res => {
          if(res.data && res.data.success){
            this.setState({
              payment_id: res.data.payment_id
            }, () => {
              this.getPaymentDetail()
              this.setState({
                isLoading: false
              })
            })
          }else {
            this.setState({
              isLoading: false
            })
          }
        })
    })
  }

  render(){
    const room = this.state.room
    return (
      <ImageBackground source={require('../../../assets/images/tree2.png')} style={styles.ImageBackground}>
        <NavigationEvents
          onDidFocus={() => {
            this.setState({
              isLoading: true
            }, () => {
              this.getPaymentDetail()
            })
          }}
        />
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
        <View style={{padding: 16, flex: 0.9}}>
          <ScrollView contentContainerStyle={styles.detialContainer}>
            <View style={styles.borderBottom}>
              <Text style={[styles.mainText, {fontSize: 18, textAlign: 'center'}]}>{t('payment_detail')}</Text>
              {
                this.state.payment && this.state.payment.detail.length > 0 &&
                  <Text style={[styles.mainText, {fontSize: 14, textAlign: 'center'}]}>
                    {t('room')} {room ? room : ''}
                  </Text>
              }              
            </View>

            <View style={styles.borderBottom}>
              <View style={{flexDirection: 'row', display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8}}>
                <Text style={[styles.mainText, {color: '#269A21'}]}>{t('list_unit')}</Text>
                <Text style={[styles.mainText, {color: '#269A21'}]}>{t('amount')}</Text>
              </View>

            {
              this.state.payment && this.state.payment.detail && this.state.payment.detail.length > 0 &&
              <FlatList
                data={this.state.payment.detail}
                renderItem={({ item }) => this.renderItem(item)}
                pagingEnabled={true}
                extraData={this.state}
                keyExtractor={this._keyExtractor}
              />
            } 
            </View>

            <View style={{flexDirection: 'row', justifyContent: 'flex-end', marginTop: 10, paddingHorizontal: 10}}>
              <Text style={[styles.mainText, {textAlign: 'right',}]}>{t('total')}</Text>
              <Text style={[styles.mainText, {fontWeight: '500', paddingLeft: 10}]}>
                {this.state.payment && this.state.payment.total_cost ? parseFloat(this.state.payment.total_cost).toLocaleString() : 0} {t('baht')}
                </Text>
            </View>

            {
              !this.state.couponSelected &&
                <View style={styles.useCouponContainer}>
                  <View>
                    <Text style={[styles.mainText, {fontSize: 16}]}>{t('use_coupon')}</Text>
                    {
                      this.state.coupon_list?.length === 0 && <Text style={[styles.mainText, {color: 'red', fontSize: 10}]}>{t('coupon_not_found')}</Text>
                    }                
                  </View>
                  <TouchableOpacity style={{backgroundColor: this.state.coupon_list?.length === 0 ? 'lightgrey' : '#269A21', borderRadius: 5}} 
                                    onPress={() => this.visibleCoupon()}
                                    disabled={this.state.coupon_list?.length === 0}
                  >
                    <Text style={[styles.mainText, {color: 'white', paddingHorizontal: 25, paddingVertical: 8}]}>{t('select')}</Text>
                  </TouchableOpacity>
                </View>
            }

            {
              this.state.couponSelected &&
              <View>
                <Text style={[styles.mainText, {fontSize: 16, marginVertical: 10}]}>{t('coupon_selected')}</Text>
                <View style={styles.couponCard}>
                  <View style={{flexDirection: 'row', alignItems: 'center'}}>
                    <FastImage source={{uri: this.state.couponSelected.image_reward}} style={{width: 50, height: 50 }} resizeMode={'contain'}/>
                    <View style={{marginLeft: 10}}>
                      <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                        <Text style={[styles.mainText, {fontSize: 16, marginRight: 5}]}>{this.state.couponSelected.reward_name}</Text>
                        <Text style={[styles.mainText, {fontSize: 16}]}>{this.state.couponSelected.value} {this.state.couponSelected.discount_type === 'percent' ? '%' : t('baht')}</Text>
                      </View>
                      <Text style={[styles.mainText, {color: '#FF2D55'}]}>{this.state.couponSelected.detail}</Text>
                    </View>
                  </View>
                
                  <TouchableOpacity onPress={() => this.removeCoupon()}>
                    <IconMaterial name="close-circle-outline" size={18} color="#FF2D55"/>
                  </TouchableOpacity>
                </View>
              </View>
            }
            
          </ScrollView>
        </View>

        <View style={{padding: 16, flex: 0.1}}>
          <TouchableOpacity style={{backgroundColor: '#145EB3', paddingVertical: 12, borderRadius: 5}}
                            // onPress={() => this.props.navigation.navigate('PaymentConfirm', {payment_id: this.state.new_payment_id ? this.state.new_payment_id : this.state.payment_id, room: this.state.room})}
                            onPress={() => this.props.navigation.navigate('Payment', {payment_id: this.state.payment_id })}
          >
            <Text style={{color: 'white', textAlign: 'center', fontFamily: 'Prompt-Regular'}}>{t('confirm_pay')}</Text>
          </TouchableOpacity>
        </View>

         <Modal animationType="none"
              transparent={true}
              visible={this.state.modalVisible}
              >
          <View style={styles.couponContainer}>
              <View style={styles.couponBox}>
                <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                  <Text style={[styles.mainText, {fontSize: 18, marginBottom: 10}]}>
                    {t('choose_coupon')}
                  </Text>
                  <TouchableOpacity onPress={() => this.setState({modalVisible: false, couponHighlight: null})}>
                    <IconFontawesome name="close" color="#269A21" size={16}/>
                  </TouchableOpacity>
                </View>
                
                <FlatList
                    data={this.state.coupon_list}
                    renderItem={({ item }) => (
                      <TouchableOpacity 
                        style={[styles.couponCard, this.state.couponHighlight && this.state.couponHighlight.id === item.id ? {}: {backgroundColor: '#FAFAFA', borderColor: '#00000040'}]}
                        onPress={() => this.setState({couponHighlight: item})}>
                        <FastImage source={{uri: item.image_reward}} style={{width: 50, height: 50 }} resizeMode={'contain'}/>
                        <View style={{marginLeft: 10, flex: 1}}>
                          <View style={{flexDirection: 'row', flex: 1, justifyContent: 'space-between'}}>
                            <Text style={[styles.mainText, {fontSize: 16, flex: 0.7}]}>{item.reward_name}</Text>
                            <Text style={[styles.mainText, {fontSize: 16, flex: 0.3}]}>{item.value} {item.discount_type === 'percent' ? '%' : t('baht')} </Text>
                          </View>
                          <Text style={[styles.mainText, {color: '#FF2D55'}]}>{item.detail}</Text>
                        </View>
                      </TouchableOpacity>
                    )}
                    pagingEnabled={true}
                    extraData={this.state.coupon_list}
                    keyExtractor={(item, index) => 'coupon_' + index}
                    ListEmptyComponent={() =>
                      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', margin: 16,padding:16,borderRadius:5,backgroundColor:'white'}}>
                        <Text style={{fontSize: 16}}> {t('coupon_not_found')} </Text>
                      </View>
                    }
                />

                <TouchableOpacity 
                  onPress={() => this.useCoupon()}
                  style={{
                    backgroundColor: this.state.coupon_list.length === 0 || this.state.couponHighlight === null ? 'grey' : '#269A21', 
                    marginTop: 10,
                    borderRadius: 5
                  }}
                  disabled={this.state.coupon_list.length === 0 || this.state.couponHighlight === null}
                >
                  <Text style={[styles.mainText, {color: 'white', paddingVertical: 12, textAlign: 'center'}]}>
                    {t('confirm_coupon')}
                  </Text>
                </TouchableOpacity>
                
              </View>
          </View>
        </Modal>
      </ImageBackground>
    )
  }
}

const styles = StyleSheet.create({
  contentContainer: {
    backgroundColor: '#EEFFD7',
    paddingVertical: 0,
    flexGrow: 1,
  },
  detialContainer: {
    backgroundColor: 'white',
    borderRadius: 5,
    padding: 15,
    flexGrow: 1
  },
  ImageBackground: {
    backgroundColor:'#EEFFD7',
    flex: 1
  },
  borderBottom: {
    borderBottomWidth: 1,
    borderColor: '#EAEAF4',
    padding: 10
  },
  mainText: {
    color: '#00420A',
    fontFamily: 'Prompt-Regular'
  },
  useCouponContainer: {
    backgroundColor: '#E6FFC2',
    padding: 8,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 16
  },
  couponContainer: {
    flex:1,
    backgroundColor:'#00000080',
    justifyContent:'center',
    alignItems:'center'
  },
  couponBox: {
    width: '90%',
    maxHeight: '80%',
    backgroundColor:'white',
    borderRadius:5,
    padding:17
  },
  couponCard: {
    backgroundColor: '#FDFFA2',
    padding: 8,
    // flex: 1,
    flexDirection: 'row',
    borderLeftWidth: 4,
    borderColor: '#FFCC00',
    borderRadius: 5,
    marginBottom: 8,
    justifyContent: 'space-between',
    alignItems: 'center',
  }
})

export default PaymentDetail;