import React, {Component} from 'react'
import {Alert, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import IconMaterial from "react-native-vector-icons/MaterialCommunityIcons";
import LinearGradient from "react-native-linear-gradient";
import {BackgroundImage} from "../../components/BackgroundImage";
import Image from 'react-native-fast-image'
import {t} from "../../utils/i18n";
import Popup from "../../components/Popup";
import {getRewardDetail, getUserProfile, redeemReward, useMyReward} from "../../api/UserApi";
import IndicatorLoading from "../../components/IndicatorLoading";
import {bindActionCreators} from "redux";
import {appSetUser} from "../../redux/app/action";
import {connect} from "react-redux";
import moment from "moment";

class RewardDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleConfirm: false,
      canScan: false,
      data: null,
      isLoading: false,
      point: 0,
      disabled: false
    }
  }

  componentDidMount() {
    this.setState({
      isLoading: true
    }, () => {
      Promise.all([
        this.getRewardDetail(),
        this.getUserProfile()
      ]).then(res => {
        this.setState({
          isLoading: false
        })

        let expired_at = moment(this.state.data.end_date).format('YYYY-MM-DD')
        let today = moment().format('YYYY-MM-DD')

        if(moment(expired_at).isBefore(moment(today)) || (!this.props.navigation.state.params.is_my_reward && (parseInt(this.state.point) < parseInt(this.state.data.points_to_redeem)))){
              this.setState({
                disabled: true
              })
            }
      })
    })
  }

  async getRewardDetail () {
    return await getRewardDetail(this.props.navigation.state.params.id, this.props.navigation.state.params.is_my_reward)
      .then(res => {
        if(res.ok){
          let data = res.data;
          if(this.props.navigation.state.params.is_my_reward){
              data = {
                points_to_redeem: data.points_used,
                name: data.reward_name,
                end_date: data.expired_date,
                ...data
              }
          }

          this.setState({
            data: data
          })
        }
      })
  };

  async getUserProfile () {
    return await getUserProfile()
      .then(res => {
        if(res.data && res.ok){
          this.setState({
            point: res.data.point_balance,
          }, () => {
            let user_data = this.props.user;
            user_data = {
              ...user_data,
              point: this.state.point
            }
            this.props.appSetUser(user_data)
          })
        }
      });
  }

  submitRedeem = () => {
    if(this.state.data && this.state.data.id){
      this.setState({
        isLoading: true,
        visibleConfirm: false
      }, () => {
        redeemReward(this.state.data.id)
        .then(res => {
          if(res.ok && res.data && res.data.success){
            Alert.alert('Redeem successfully', '', [
              {
                text: 'ok',
                onPress: () => {
                  this.setState({
                    isLoading: false
                  })
                  this.props.navigation.goBack()
                }
              }
            ]);
          }else {
            let message = res.data && res.data.message ? res.data.message : ''
            Alert.alert('Redeem Unsuccessfully', message, [
              {
                text: 'ok',
                onPress: () => {
                  this.setState({
                    isLoading: false
                  })
                }
              }
            ])
          }
        })
      })
    }
  };

  clickRedeem = () => {
    this.setState({
      visibleConfirm: true
    })
  };

  confirmUseReward = () => {
    Alert.alert(t('confirm_coupon'), '', [
      { text: t('cancel'), style: 'cancel' },
      {
        text: t('ok'),
        onPress: () => {
          this.state.data && this.state.data.use_by_qr ? this.scanQr() : this.useMyReward()
        }
      }
    ]
  );
  }

  scanQr = () => {
    this.props.navigation.navigate('ScanCoupon', {id: this.props.navigation.state.params.id, use_qr_with_in_time: this.state.data.use_qr_with_in_time})
  };

  useMyReward = () => {
    if(this.state.data && this.state.data.id){
      useMyReward(this.state.data.id) 
        .then(res => {
          if(res.ok && res.data && res.data.success){
            Alert.alert('Redeem successfully', '', [
              {
                text: 'ok',
                onPress: () => {
                  this.props.navigation.goBack()
                }
              }
            ]);
          }else {
            Alert.alert('Redeem unsuccessfully, Please retry again later.', '', [
              {
                text: 'ok'
              }
            ])
          }
        })
    }
  }

  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
          <LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#FFA800', '#E46F00']}
                          style={styles.pointContain}
          >
            <Text style={styles.textStyle}>{this.state.point} Points</Text>
            <IconMaterial name="star-circle-outline" color="white" size={40}/>
          </LinearGradient>
          <View style={styles.rewardContain}>
            <View style={styles.detailRewardContain}>
              <View style={{height: '85%'}}>
                <Image source={{uri: this.state.data && this.state.data.image_reward ? this.state.data.image_reward : ''}} style={{flex: 1}} resizeMode={'contain'}/>
              </View>
              <View style={{height: '15%', padding: 8}}>
                <Text style={{fontFamily: 'Prompt-Regular', fontSize: 16}}>
                  {this.state.data && this.state.data.name ? this.state.data.name : ''}
                </Text>
              </View>
            </View>
            <View style={styles.redeemCondition}>
              <View style={{flex: 1, borderRightWidth: 1, borderColor: 'white', flexDirection: 'column', justifyContent: 'space-between'}}>
                <Text style={[styles.textStyle, styles.textBody, {textAlign: 'left'}]}>Redeem</Text>
                <Text style={[styles.textStyle, styles.textBody, {textAlign: 'left'}]}>{this.state.data && this.state.data.points_to_redeem} Points</Text>
              </View>
              <View style={{flex: 1, paddingLeft: 20, flexDirection: 'column', justifyContent: 'space-between'}}>
                <Text style={[styles.textStyle, styles.textBody, {textAlign: 'left'}]}>Until</Text>
                <Text style={[styles.textStyle, styles.textBody, {textAlign: 'left'}]}>
                  {this.state.data && this.state.data.end_date ? moment(this.state.data.end_date, 'YYYY-MM-DD').format('DD MMM YYYY') : '-'}
                </Text>
              </View>
            </View>
          </View>

          <View style={styles.rewardFooter}>
            <TouchableOpacity style={{flexDirection: 'row', justifyContent: 'space-between', padding: 15}}
                              onPress={() => this.props.navigation.navigate('RewardTermCondition', {id: this.props.navigation.state.params.id})}
            >
              <Text style={[styles.textStyle, styles.textBody]}>Terms & Conditions</Text>
              <Text style={[styles.textStyle, styles.textBody]}> > </Text>
            </TouchableOpacity>

            <View style={{marginBottom: 25, paddingHorizontal: 15}}>
              {
                this.props.navigation.state.params.is_history || this.state.data?.use_by === 'auto'
                  ? <View/>
                  : this.props.navigation.state.params.is_my_reward
                    ? this.state.data?.use_by === 'manual' && <TouchableOpacity onPress={() => { this.confirmUseReward() }}
                                        disabled={this.state.disabled}
                                        style={[styles.btnRedeem, this.state.disabled ? {backgroundColor: 'grey'} : {}]}>
                      <Text style={[styles.textStyle, styles.textBody, {textAlign: 'center'}]}>ใช้ทันที</Text>
                    </TouchableOpacity>
                    : <TouchableOpacity onPress={() => {this.clickRedeem()}}
                                        disabled={this.state.disabled}
                                        style={[styles.btnRedeem, this.state.disabled ? {backgroundColor: 'grey'} : {}]}>
                      <Text style={[styles.textStyle, styles.textBody, {textAlign: 'center'}]}>{t('redeem_point')}</Text>
                    </TouchableOpacity>
              }
            </View>
          </View>

          <Popup
            title={t('confirm_redeem')}
            message={`${this.state.data && this.state.data.points_to_redeem ? this.state.data.points_to_redeem : 0} Points`}
            styleTitle={{textAlign: 'center', color: 'black', fontSize: 20}}
            styleMessage={{textAlign: 'center', color: '#FF9500', fontWeight: 'bold', fontSize: 20}}
            modalVisible={this.state.visibleConfirm}
            onCancel={() => this.setState({visibleConfirm: false})}
            onConfirm={() => this.submitRedeem()}
            styleFooter={{justifyContent: 'center', marginTop: 0}}
          />
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    );
  }
}


const styles = StyleSheet.create({
  textStyle: {
    color: 'white',
    fontFamily: 'Prompt-Regular',
    fontSize: 20,
    textAlign: 'right',
    fontWeight: '500',
    marginRight: 5
  },
  textBody: {
    fontSize: 16
  },
  pointContain: {
    justifyContent: 'flex-end',
    paddingVertical: 12,
    paddingHorizontal: 5,
    flexDirection: 'row',
    alignItems: 'center'
  },
  rewardContain: {
    flex: 0.8,
    height: 300,
    borderRadius: 6,
    paddingHorizontal: 16,
    paddingVertical: 8
  },
  detailRewardContain: {
    borderRadius: 6,
    backgroundColor: 'white',
    height: '78%'
  },
  redeemCondition: {
    backgroundColor: '#FFFFFF33',
    height: '16%',
    flexDirection: 'row',
    borderRadius: 6,
    marginTop: 20,
    padding: 17
  },
  rewardFooter: {
    flex: 0.2,
    backgroundColor: '#00420A',
    flexDirection: 'column',
    justifyContent: 'space-between'
  },
  btnRedeem: {
    backgroundColor: '#269A21',
    borderRadius: 5,
    padding: 10
  }
});

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

const propSet = dispatch => bindActionCreators({
  appSetUser,
}, dispatch)

export default connect(mapDisPatchToProps, propSet)(RewardDetail)
