import React, {Component} from 'react'
import {View, StyleSheet, Alert} from "react-native";
import LinearGradient from "react-native-linear-gradient";
import {BackgroundImage} from "../../components/BackgroundImage";
import IconEvil from "react-native-vector-icons/EvilIcons";
import QRCodeScanner from 'react-native-qrcode-scanner';
import { RNCamera } from 'react-native-camera';
import CountDown from "react-native-countdown-component";
import IndicatorLoading from "../../components/IndicatorLoading";
import {scanReward, usedCoupon} from "../../api/UserApi";

class ScanCoupon extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      use_qr_with_in_time: 0.5,
      hasPermission: false,
      reward_id: 0
    }
  }

  componentDidMount() {
    let reward_id = this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.id;
    this.setState({
      reward_id
    })

    this.props.navigation.setParams({index: 2})
    usedCoupon(reward_id).then(res => {
      if(res.data && res.data.success) {
        
      }else {
        let message = res.data?.message || ''
        Alert.alert('Unsuccessfully', message, [
          {
            text: 'ok',
            onPress: () => {
              this.props.navigation.navigate('RewardDetail', {id: reward_id.id, is_my_reward: true, is_history: false})
            }
          }
        ])
      }
    })
  }

  componentWillMount(){
    let use_qr_with_in_time = this.props.navigation && this.props.navigation.state && this.props.navigation.state.params && this.props.navigation.state.params.use_qr_with_in_time;
    this.setState({
      use_qr_with_in_time,
    })
  }

  onSuccess = (event) => {
    let code = event.data;
    this.setState({
      isLoading: true
    }, () => {
      scanReward(this.state.reward_id, code)
        .then(res => {
          if(res.ok && res.data && res.data.success){
            Alert.alert('Redeem successfully', '', [
              {
                text: 'ok',
                onPress: () => {
                  this.setState({
                    isLoading: false
                  }, () => {
                    Alert.alert(`Redeem Code: ${res.data.code}`, '', [
                      {
                        text: 'ok',
                        onPress: () => {
                          this.props.navigation.navigate('MyRewards', {index: 2})
                        }
                      }
                    ])
                  })
                }
              }
            ]);
          }else {
            let message = res.data && res.data.message ? res.data.message : ''
            Alert.alert('Redeem Unsuccessfully', message, [
              {
                text: 'ok',
                onPress: () => {
                  this.setState({
                    isLoading: false
                  })
                }
              }
            ])
          }
      })
    })
  };


  render() {
    return (
      <LinearGradient colors={['#3AA40C', '#2C7C0B']} style={{
        flex: 1,
        width: null,
        height: null,
        resizeMode: 'cover'
      }}>
        <BackgroundImage>
          <View style={this.state.use_qr_with_in_time > 0 && styles.pointContain}>
            {
              this.state.use_qr_with_in_time > 0 &&
              <View style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
                <IconEvil name="clock" color="white" size={35} />
                <CountDown
                  until={60 * this.state.use_qr_with_in_time}
                  // onFinish={() => this.props.navigation.navigate('RewardDetail')}
                  onFinish={() => this.props.navigation.navigate('MyRewards', {index: 2})}
                  digitStyle={{background: 'transparent'}}
                  digitTxtStyle={{color: 'white', fontFamily: 'Prompt-Regular'}}
                  separatorStyle={{color: 'white'}}
                  timeToShow={['M', 'S']}
                  timeLabels={{m: null, s: null}}
                  size={24}
                  showSeparator
                />
              </View>
            }
          </View>

          <View style={{height: '100%'}}>
            <QRCodeScanner
              onRead={this.onSuccess}
              reactivate={true}
              flashMode={RNCamera.Constants.FlashMode.auto}
              cameraStyle={{width: '100%', height: '100%'}}
              reactivateTimeout={2000}
            />
          </View>
        </BackgroundImage>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </LinearGradient>
    )
  }
}

const styles = StyleSheet.create({
  textStyle: {
    color: 'white',
    fontFamily: 'Prompt-Regular',
    fontSize: 24,
    textAlign: 'center',
    fontWeight: '600'
  },
  pointContain: {
    paddingVertical: 8,
    paddingHorizontal: 5,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#006910',
    height: 60
  }
});
export default ScanCoupon
