import Axios from 'axios';
import moment from 'moment';
import React from 'react';
import { Alert, Image, Linking, ScrollView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import HTML from 'react-native-render-html';
import { connect } from 'react-redux';
import session from '../function/session';
import requestParams from '../helper/requestParams';
import ActionType from '../redux/globalActionType';
import MyStatusBar from './MyStatusBar';
import i18n from 'i18n-js';
import Spinner from 'react-native-loading-spinner-overlay';

class RewardDetail extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            image: '',
            title: '',
            subtitle: '',
            content: '',
            expire: '',
            code: '',
            used: '',
            dateNow: '',
            value: '',
            cur_time: '',
            exp_time: '',
            spinner: false
        }
    }

    componentDidMount() {
        this.detailReward()
    }

    detailReward() {
        let params = Object.assign(requestParams, {
            session_id: this.props.session_id,
            reward_id: this.props.route.params.rewardId
        })
        Axios.post(this.props.BASE_URL + 'crm/v2/reward/get_detail', params).then(res => {
            let exp_time = new Date(res.data.reward.expire_time)
            let cur_time = new Date()

            let expire_date = moment(res.data.reward.expire_time).format('DD MMMM YYYY')

            this.setState({
                image: res.data.reward.reward.content_image,
                title: res.data.reward.reward.title,
                subtitle: res.data.reward.reward.subtitle,
                content: res.data.reward.reward.content,
                expire: expire_date,
                code: res.data.reward.verification_number,
                used: res.data.reward.used,
                value: res.data.reward,
                cur_time: cur_time,
                exp_time: exp_time

            })

        }).catch(error => {
            const { navigation } = this.props
            let response = error.response.data
            session(response, navigation)
            Alert.alert(response.msg);
        })
    }


    handleVoucherSelect() {
        //SPINNER ON 
        this.setState({
            spinner: true,
        })
        //CEK TYPE TRANSAKSINYA DELIVERY OR PICKUP, DICEK UNTUK DI MASUKAN DI PARAMATER PEMANGGILAN API
        let type_trans = ""
        if (this.props.type_pickup == true) {
            type_trans = 'Pickup'
        } else {
            type_trans = 'Delivery'
        }

        let params = {
            session_id: this.props.session_id,
            trans_type: type_trans,
            order_item: this.props.order_item,
            reward_id: this.props.route.params.rewardId,
            delivery_charge: this.props.grabamount,
        }

        // MULAI DISINI PEMANGGILAN API DI MULAI, KALAU BERHASIL SET VALUE VOUCHER NYA DAN SPINER DIMATIKAN, KALAU GAGAL CABUT SESSION VOUCHER DAN SPINNER DI MATIKAN
        Axios.post(this.props.BASE_URL + 'crm/v2/reward/get_value', params).then(res => {

            let voucherProps = {
                value_voucher: res.data.reward,
                voucher: res.data.reward
            }
            this.props.setVoucher(voucherProps);
            this.setState({
                spinner: false,
            })

            this.props.navigation.navigate('Home', { screen: 'MENU' })

        }).catch(error => {
            try {
                let response = error.response.data;
                if (response.code == "REWARD_CANNOT_BE_USED") {
                    this.setState({
                        spinner: false,
                    })
                    this.props.navigation.navigate('Home', { screen: 'MENU' })
                } else {
                    Alert.alert(
                        '',
                        response.msg,
                        [
                            { text: "OK", onPress: () => this.setState({ spinner: false }) }
                        ],
                    );
                    
                    // FUNGSI REDUX UNTUK HAPUS VOUCHER
                    this.props.removeVoucher()
                }

            } catch (error) {
                Alert.alert("", error.toString())
            }
        })

    }

    useVoucher() {
        this.handleVoucherSelect()

    }

    useDVoucher() {
        this.props.navigation.navigate('Reward History')
    }


    render() {
        return (
            <View style={styles.container}>
                <Spinner visible={this.state.spinner} textContent={'Loading...'} textStyle={{ color: "white" }} />
                <MyStatusBar />
                <ScrollView>
                    <View style={styles.images}>
                        <Image style={{ height: 360, width: '100%' }} source={this.state.image ? { uri: this.state.image } : null} resizeMode='contain' />
                        <View style={styles.voucher_code}>
                            <Text style={styles.text_voucher}>{i18n.t('codeVoucher')}</Text>
                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 20, textAlign: 'center', marginBottom: 5, top: 15 }}>{this.state.code}</Text>
                        </View>
                        <View style={styles.expire_time}>
                            <View style={{ flex: 0.5 }}>
                                <Text style={styles.text_expire}>{i18n.t('expiredOn')}</Text>
                            </View>
                            <View style={{ flex: 0.5 }}>
                                <Text style={{ fontFamily: 'Gotham-Light', color: 'white', fontSize: 14, textAlign: 'right', marginBottom: 5, top: 5, paddingRight: 12 }}>{this.state.expire}</Text>
                            </View>
                        </View>

                    </View>

                    <View style={styles.content}>
                        <View style={{ marginRight: 5, marginLeft: 5 }}>
                            <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 15 }}>{this.state.title}</Text>
                        </View>
                        <View
                            style={{ marginHorizontal: 20 }}
                        >

                            <HTML html={this.state.content}
                                tagsStyles={{ p: { fontSize: 12, color: '#838383', fontFamily: 'Gotham-Light' }, li: { fontSize: 12, color: '#838383', fontFamily: 'Gotham-Light' }, ul: { fontSize: 12, color: '#838383', fontFamily: 'Gotham-Light', marginTop: 10 }, blockquote: { backgroundColor: "#f1f1f1", padding: 12, paddingBottom: 0, marginTop: 6 } }}
                                ignoredTags={['br']}
                                ignoredStyles={['font-family']}
                                onLinkPress={(event, href) => {
                                    Linking.openURL(href)
                                }} />
                        </View>
                    </View>
                    <View style={styles.content}>
                        {this.state.cur_time > this.state.exp_time ? (
                            <View style={{ flex: 1, height: 50, marginRight: 70, marginLeft: 70, justifyContent: 'center' }}>
                                <View style={{ height: 40, borderRadius: 10, backgroundColor: 'red' }}>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 11 }}>{i18n.t('expiredLabel')}</Text>
                                </View>
                            </View>
                        )
                            : this.state.used == 0 ? (
                                <View style={{ flex: 1, height: 50, marginRight: 70, marginLeft: 70, justifyContent: 'center' }}>
                                    <TouchableOpacity onPress={() => this.useVoucher()}>
                                        <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368' }}>
                                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 11 }}>{i18n.t('useVoucher')}</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                            ) : (
                                    <TouchableOpacity onPress={() => this.useDVoucher()}>
                                        <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368' }}>
                                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 11 }}>{i18n.t('usedVoucher')}</Text>
                                        </View>
                                    </TouchableOpacity>
                                )}

                    </View>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: 'white',
    },
    body: {
        flex: 1,
        backgroundColor: 'red'
    },

    voucher_code: {
        fontFamily: 'Gotham-Black',
        height: 70,
        marginLeft: 20,
        marginRight: 20,
        backgroundColor: '#CFB368',
        flex: 1,
        marginTop: -100

    },

    expire_time: {
        fontFamily: 'Gotham-Light',
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginLeft: 20,
        marginRight: 20,
        height: 30,
        justifyContent: 'center',
        backgroundColor: '#838383',
    },

    text_voucher: {
        fontFamily: 'Gotham-Light',
        fontSize: 14,
        marginLeft: 10,
        top: 5,
        color: 'white'
    },

    text_c_voucher: {
        fontFamily: 'Gotham-Black',
        textAlign: 'center',
        fontWeight: 'bold',
        fontSize: 30,
        top: 5,
        color: 'white'
    },

    text_expire: {
        fontFamily: 'Gotham-Light',
        fontSize: 14,
        marginLeft: 10,
        top: 5,
        color: 'white'
    },

    text_c_expire: {
        fontFamily: 'Gotham-Black',
        textAlign: 'center',
        fontWeight: 'bold',
        fontSize: 30,
        top: 5,
        color: 'white',
    },

    content: {

        flex: 1,
        marginBottom: 20,
    },
    button: {
        flex: 1,
        height: 60,
        backgroundColor: '#2ead28',
        borderRadius: 5,
    },
    images: {
        flex: 1,
    }
})


const mapDispatchToProps = (dispacth) => {
    return {

        setVoucher: (voucherProps) => dispacth({
            type: ActionType.SET_VOUCHER,
            data: {

                voucher: voucherProps.voucher,
                value_voucher: voucherProps.value_voucher,

            }
        }),
        removeVoucher: () => dispacth({
            type: ActionType.REMOVE_VOUCHER
        }),
    }
}

const mapStateToProps = (state) => {
    return {

        session_id: state.session_id,
        lat: state.lat,
        long: state.long,
        BASE_URL: state.BASE_URL,
        outlet_detailadress: state.outlet_detailadress,
        home_address: state.home_address,
        type_pickup: state.type_pickup,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        session_id: state.session_id,
        outlet_id: state.outlet_id,
        name_outlet: state.name_outlet,
        value_voucher: state.value_voucher,
        voucher: state.voucher,
        order_quantity: state.order_quantity,
        order_total: state.order_total,
        order_item: state.order_item,
        quantity: state.quantity,
        address: state.address,
        addressId: state.addressId,
        grabtype: state.grabtype,
        grabamount: state.grabamount,
        grabpickup: state.grabpickup,
        grabdropoff: state.grabdropoff,
        grabdestination: state.grabdestination,

    }
}

export default connect(mapStateToProps, mapDispatchToProps)(RewardDetail);
