import React, { Component } from 'react'
import {ScrollView, StyleSheet, TouchableOpacity, Alert, PermissionsAndroid, ImageBackground, Platform} from "react-native";
import {CameraRoll} from '@react-native-camera-roll/camera-roll'
import {View} from "native-base";
import Text from '../../components/Text';
import { payment_detail } from '../../api/UserApi';
import ViewShot, { captureRef } from "react-native-view-shot";
import IndicatorLoading from '../../components/IndicatorLoading';
import QRCode from 'react-native-qrcode-svg';
import { t } from '../../utils/i18n';
import Image from 'react-native-fast-image'

class PaymentScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      text: '',
      payment_data: {},
      payment_id: this.props.navigation.getParam('payment_id', 'NO ITEM')
    }
    this.snapScreen = this.snapScreen.bind(this)
  }

  componentDidMount(){
    console.log('payment id ---------> ',this.state.payment_id);
    this.setState({isLoading:true})
    payment_detail(this.state.payment_id)
    .then( res => {
      if(res.data && res.data.success){
        this.setState({
          payment_data: res.data
        },() => {
          this.setState({isLoading: false})
        })
      }else {
        Alert.alert(res.data.message, '', [{
          text: 'ok',
          onPress: () => {
            this.setState({
              isLoading: false
            }, () => {
              this.props.navigation.goBack()
            })
          }
        }])
      }
    })
  };

  async hasAndroidPermission() {
    const getCheckPermissionPromise = () => {
      if (Platform.Version >= 33) {
        return Promise.all([
          PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES),
          PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO),
        ]).then(
          ([hasReadMediaImagesPermission, hasReadMediaVideoPermission]) =>
            hasReadMediaImagesPermission && hasReadMediaVideoPermission,
        );
      } else {
        return PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
      }
    };
    
    const hasPermission = await getCheckPermissionPromise();
    if (hasPermission) {
      return true;
    }
    const getRequestPermissionPromise = () => {
      if (Platform.Version >= 33) {
        return PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES,
          PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO,
        ]).then(
          (statuses) =>
            statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_IMAGES] ===
              PermissionsAndroid.RESULTS.GRANTED &&
            statuses[PermissionsAndroid.PERMISSIONS.READ_MEDIA_VIDEO] ===
              PermissionsAndroid.RESULTS.GRANTED,
        );
      } else {
        return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE).then((status) => status === PermissionsAndroid.RESULTS.GRANTED);
      }
    };

    return await getRequestPermissionPromise();
  }  

  async snapScreen() {
    try {
      if(Platform.OS == 'android' && !(await this.hasAndroidPermission())){
        return
      }else{
        this.viewshot.capture()
          .then(
            uri => {
              console.log(' ------------> ',uri)
              return CameraRoll.save(uri, { type: 'photo' })
                      .then(Alert.alert(null, t('save_photo'),[{text: t('ok')}]))
            }
          )
      }
    } catch (err) {
      console.warn(err);
    }

  }

  render(){
    return(
      <ImageBackground source={require('../../../assets/images/tree2.png')} style={{width: '100%', height: '100%', backgroundColor:'#EEFFD7'}}>
        <ViewShot style={{flex: 1}} options={{format: "jpg", quality: 1}} ref={ref => this.viewshot = ref}>
          <ScrollView contentContainerStyle={styles.contentContainer}>
            <View style={styles.QrContainer}>
              <View style={styles.headerQr}>
                <Image source={require('../../../assets/images/icon_payment.png')} style={{height: 40}} resizeMode={'contain'}/>
              </View>
              <Image source={require('../../../assets/images/icon_promptpay.png')} style={{height: 35, marginVertical: 18}} resizeMode={'contain'}/>
              <Text style={{fontSize: 18,color:'#00420A', textAlign: 'center'}}>{t('scan_to_pay')}</Text>
              <View style={{flex: 0.9, alignItems: 'center'}}>
                {/* <Image source={{uri: this.state.payment_data.qr}} style={{flex: 1}} resizeMode="contain"/> */}
                <View style={{paddingVertical:10}}>
                    <QRCode
                      value={this.state.payment_data.qr}
                      size={140}
                      color='black'
                      backgroundColor='white'/>
                  </View>
                <View style={{alignItems: 'center'}}>
                  <Text style={{fontSize: 12,color:'#000000'}}>ชื่อบัญชี : {this.state.payment_data.receiver_name}</Text>
                  <Text style={{fontSize: 12,color:'#000000'}}>{t('account')} : {this.state.payment_data.receiver_account}</Text>
                  <Text style={{fontSize: 10,color:'#00000080'}}>{t('ref_no')}: { this.state.payment_data.payment != null && this.state.payment_data.payment.reference}</Text>
                  <Text style={{fontSize: 10,color:'#00000080'}}>{t('ref_no')} 2 : { this.state.payment_data.payment != null && this.state.payment_data.ref2}</Text>
                  <View style={{margin: 10,height:1,width: '90%',backgroundColor:'#D7D7D7'}}/>
                  <Text style={{fontSize: 13,color:'#000000'}}>{t('account_name')}</Text>
                  <Text style={{fontSize: 24,color:'#000000'}}>{this.state.payment_data != {} && Intl.NumberFormat().format(this.state.payment_data.total_cost)} {t('baht')}</Text>
                  <View style={{margin: 10,height:1,width: '100%',backgroundColor:'#D7D7D7'}}/>
                  <Text style={{fontSize: 10,color:'#00000080',marginBottom: 10}}>Accepts all banks | {t('support_all_bank')}</Text>
                </View>
              </View>
            </View>
          </ScrollView>
        </ViewShot>

        <View style={{flex: 0.1, justifyContent: 'center'}}>
          <TouchableOpacity style={{backgroundColor:'#269A21',height: 40,justifyContent:'center',alignItems:'center',borderRadius:5, marginHorizontal: 20}}
                            onPress={this.snapScreen}>
            <Text style={{color:'white',fontSize:14}}>{t('save')}</Text>
          </TouchableOpacity>
        </View>
        <IndicatorLoading loadingVisible={this.state.isLoading}/>
      </ImageBackground>
    )
  }
}


const styles = StyleSheet.create({
  circleShapeView: {
    width: 32,
    height: 32,
    borderRadius: 100,
    justifyContent: 'center',
    alignItems: 'center'
  },
  contentContainer: {
    flex:1,
    padding: 20
  },
  colorTextPayment: {
    color: '#7CBB33'
  },
  QrContainer: {
    flex: 1,
    backgroundColor:'white',
    borderRadius:10
  },
  headerQr: {
    width: '100%',
    backgroundColor:'#29558D',
    height: 55,
    borderTopLeftRadius:10,
    borderTopEndRadius:10,
    justifyContent:'center'
  }
})

export default PaymentScreen
