import { MaterialIcons } from '@expo/vector-icons';
import Axios from 'axios';
import Constants from 'expo-constants';
import * as Device from 'expo-device';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import i18n from 'i18n-js';
import React from 'react';
import { ActivityIndicator, Alert, Image, ImageBackground, ScrollView, StatusBar, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { Card } from 'react-native-shadow-cards';
import Toast from 'react-native-tiny-toast';
import NumberFormat from 'react-number-format';
import { connect } from 'react-redux';
import requestParams from '../helper/requestParams';
import ActionType from '../redux/globalActionType';
import CustomIosStatusBar from './CustomIosStatusBar';


class Account extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: "",
            points: "",
            balance: "",
            img_card: "",
            member_since: "",
            account_number: "",
            expire_date: "",
            premium: "",
            my_lat: 0,
            my_long: 0,
            full_name: '',
            indicator: true,
            clickSettings: 0,
            old_balance_claimed: false,
            old_balance: 0,
            is_expired: false,
            card_number: "",
        }
    }

    componentDidMount() {

        try {

            this._getProfile()
            this._unsubscribe = this.props.navigation.addListener('focus', () => {
                this.setState({
                    indicator: true
                })
                this._getProfile()
            });
        } catch (error) {
            Alert.alert('Error' + error)
        }

    }

    componentWillUnmount() {
        try {
            this._unsubscribe();
        } catch (error) {
            Alert.alert('Error : ' + error)
        }
       
    }

    _getPermissions = async () => {
        try {
            let { status } = await Permissions.askAsync(Permissions.LOCATION);
            if (status !== 'granted') {
                Alert.alert(i18n.t('accessNotPermitted'))
            } else if (Platform.OS === 'android' && !Device.isDevice) {

                Alert.alert(i18n.t('tryItRealDevice'))
            } else {
                this._getCurrentPosisition()
            }
        } catch (error) {
            Alert.alert('Error : ' + error)
        }

    }
    _getCurrentPosisition = async () => {
        try {
            this.setState({
                spinner: true,
            })
            let location = await Location.getCurrentPositionAsync({
                accuracy: Location.Accuracy.Highest
            })

            let latitude = location.coords.latitude;
            let longitude = location.coords.longitude;

            this.setState({
                my_lat: latitude,
                my_long: longitude
            })

            this._getProfile()
        } catch (error) {
            Alert.alert('Error: + ', error)
        }

    }

    logout() {

        try {
            let configProps = {
                session_id: ''
            }
            this.props.setConfig(configProps);
            this.props.navigation.replace('Login');
        } catch (error) {
            Alert.alert('ERROR : ' + error)
        }
    }

    onClickClaimCredit() {
        try {

            Alert.alert(
                "",
                i18n.t('makeSureClaimCredit'),
                [
                    {
                        text: i18n.t('alertno'),
                        onPress: () => console.log('Cancel Claim Credit'),
                        style: 'cancel',
                    },
                    {
                        text: i18n.t('alertyes'), onPress: () => this.handleClaimCredit()
                    },
                ],
                { cancelable: false },
            )
            
        } catch (error) {
            Alert.alert('Error: ' + error)
        }
    
    }

    handleClaimCredit() {
        try {
            let params = Object.assign(requestParams, {
                session_id: this.props.session_id,
            })
            Axios.post(this.props.BASE_URL + 'crm/v2/card/claim_old_balance', params).then(res => {
                Alert.alert(i18n.t('success'), i18n.t('alertclaimcredit'))
            }).catch(error => {
                let response = error.response.data
                Alert.alert(error, response.msg)
            })  
        } catch (error) {
            Alert.alert('Error : '+ error)
        }
       
    }

    _getProfile() {
        try {

            let params = Object.assign(requestParams, {
                session_id: this.props.session_id,
                lat: this.state.my_lat,
                long: this.state.my_long,
                closest_outlet: 1
            })
    
            Axios.post(this.props.BASE_URL + 'crm/v2/member/get_profile', params).then(res => {
                // console.log("INI DATANYA : " + JSON.stringify(res))
                const dataCard = res.data
                console.log(dataCard)
                let email = dataCard.email
                let point = dataCard.kaspro_point
                let balance = dataCard.kaspro_balance
                let img_card = dataCard.card_series_image
                let member_since = dataCard.member_since
                let expire = dataCard.expire_date
                let premium = dataCard.kaspro_is_premium
                let kaspro = dataCard.kaspro_account_number
                let full_name = dataCard.name
                let old_balance_claimed = dataCard.old_balance_claimed
                let old_balance = dataCard.old_balance
                let is_expired = dataCard.is_expired
                let card_number = dataCard.card_number
                let account_number = dataCard.account_number
    
                if (kaspro === "") {
    
                    let cardProps = {
                        set_card: false
    
                    }
    
                    this.props.setCardactive(cardProps)
                } else {
                    let cardProps = {
                        set_card: true
                    }
                    this.props.setCardactive(cardProps)
                }
    
                this.setState({
                    email: email,
                    points: point,
                    img_card: img_card,
                    member_since: member_since,
                    balance: balance,
                    account_number: account_number,
                    img_card: img_card,
                    expire_date: expire,
                    premium: premium,
                    full_name: full_name,
                    indicator: false,
                    old_balance_claimed: old_balance_claimed,
                    old_balance: old_balance,
                    is_expired: is_expired,
                    card_number: card_number
    
                })
    
                let setCardNumberProps = {
                    card_number: this.state.card_number
                }
                this.props.setCardNumber(setCardNumberProps)
    
            }).catch(error => {
                // const { navigation } = this.props
                // let response = error.response.data
                // session(response, navigation)
                let response = error.response.data
                // Alert.alert('',response.msg);
                Toast.show(response.msg)
            })
            
        } catch (error) {
            Alert.alert('Error :' + error)
        }
       
    }

    TransferBalance() {

        try {
            if (this.state.premium === false) {
                Alert.alert(
                    i18n.t('notPremiumYet'),
                    i18n.t('wantUpgradePremium'),
    
                    [{ text: i18n.t('alertCancel') },
                    { text: 'OK', onPress: () => this.props.navigation.navigate('Upgrade Premium') }
                    ]
                )
            } else {
                this.props.navigation.navigate('Transfer Balance');
            }
        } catch (error) {
            Alert.alert('Error : ' + error)
        }

      
    }

    handleuseBalance() {
        try {
            let params = Object.assign(requestParams, {
                session_id: this.props.session_id,
            })
            Axios.post(this.props.BASE_URL + 'crm/v2/point/check', params).then(res => {
                if (res.data.in_process_redeem == false) {
                    this.props.navigation.navigate('UseBalance')
                } else {
                    this.props.navigation.navigate('Redeem Code')
                }
            }).catch(error => {
                let response = error.response.data
                Alert.alert(error, response.msg)
            })
        } catch (error) {
            Alert.alert('Error:' + error)
        }
      
    }

    render() {
        try {
            const navigation = this.props.navigation
            return (
                <View style={styles.container}>
                    {Platform.OS === 'ios' ? (
                    <CustomIosStatusBar color='#CFB368' />
                    ) : null}
                    <ScrollView style={{ paddingTop: StatusBar.currentHeight }}>
    
                        <View style={{ flex: 1, height: 90 }}>
                            <View style={{ alignSelf: 'center' }}>
                                <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile')}>
                                    <Image
                                        style={{ height: 70, width: 70, justifyContent: 'center', top: 20 }}
                                        source={require('../assets/images/people-actv.png')}
                                    />
                                </TouchableOpacity>
                            </View>
                            <View style={{ height: 90, justifyContent: 'center' }}>
                                <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile')}>
                                    <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center' }}>
                                        {this.state.full_name}
                                    </Text>
                                </TouchableOpacity>
                                <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile')}>
                                    <Text style={{ fontFamily: 'Gotham-Light', color: '#838383', fontSize: 12, textAlign: 'center', top: 2 }}>{i18n.t('Viewprofil')}</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
    
    
                        {
                            this.props.set_card === false ? (
                                <View style={{ marginTop: 65 }}>
                                    <View style={{ flex: 1, backgroundColor: 'grey', height: 250, borderRadius: 20, marginRight: 10, marginLeft: 10, justifyContent: 'center' }}>
                                        <View style={{ justifyContent: 'center' }}>
                                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Card Activation', { cardNumber: this.state.card_number })}>
                                                <View style={{ height: 50, borderRadius: 20, backgroundColor: 'white', marginRight: 20, marginLeft: 20, }}>
                                                    <Text style={{ fontFamily: 'Gotham-Black', color: '#CFB368', fontSize: 20, textAlign: 'center', margin: 15 }}>{i18n.t('Acitvatecard')}</Text>
                                                </View>
                                            </TouchableOpacity>
                                        </View>
    
                                    </View>
                                    <View style={{ flex: 1, height: 250 }}>
                                        <TouchableOpacity style={{ top: 10, marginLeft: 15, marginRight: 15, justifyContent: 'center' }} onPress={() => this.logout()}>
                                            <View style={{ height: 40, borderRadius: 20, backgroundColor: '#CFB368', justifyContent: 'center' }}>
                                                <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center' }}>{i18n.t('logout')}</Text>
                                            </View>
                                        </TouchableOpacity>
                                        <View style={styles.v_logo}>
                                            <View style={{ flex: 1, alignSelf: 'flex-start', marginTop: 20 }}>
                                                <Image resizeMode="contain" source={require('../assets/images/daun.png')} style={styles.logo}></Image>
                                            </View>
                                            <View style={{ flex: 1 }}>
    
                                            </View>
                                        </View>
                                    </View>
                                </View>
                            ) : (
                                    <View>
                                        <View style={styles.Card}>
                                            <View style={styles.card}>
                                                <View style={styles.card}>
                                                    {
                                                        this.state.indicator ? (
                                                            <Card style={{ padding: 50, alignContent: 'center' }}>
                                                                <ActivityIndicator style={{ justifyContent: "center" }} size="large" color="#c9af6d" />
                                                            </Card>
                                                        ) : (
                                                                <>
                                                                    <Card style={{ padding: 20, alignContent: 'center' }}>
                                                                        <View style={{ flexDirection: 'row', flex: 1, paddingBottom: 5 }}>
                                                                            <View style={{ flex: 0.5 }}>
                                                                                <Text style={{ fontSize: 10, fontFamily: 'Gotham-Light' }}>{i18n.t('cardnumber')}</Text>
                                                                            </View>
                                                                            <View style={{ flex: 0.5 }}>
                                                                                {this.state.is_expired ? (
                                                                                    <Text style={{ fontSize: 10, textAlign: 'right', fontFamily: 'Gotham-Light', color: '#d34343' }}>Expired {this.state.expire_date}</Text>
                                                                                ) : (
                                                                                        <Text style={{ fontSize: 10, textAlign: 'right', fontFamily: 'Gotham-Light' }}>{i18n.t('expired')} {this.state.expire_date}</Text>
                                                                                    )
                                                                                }
                                                                            </View>
                                                                        </View>
                                                                        <View style={{ paddingHorizontal: 10 }}>
                                                                            <Text style={{ textAlign: "center", fontSize: 30, color: '#c9af6d', fontFamily: 'Gotham-Black' }}>
                                                                                {this.state.card_number}
                                                                            </Text>
                                                                        </View>
                                                                        <View style={styles.line}></View>
    
                                                                        <View style={{ flexDirection: 'row', flex: 1 }}>
                                                                            <View style={{ flex: 0.3, justifyContent: 'center' }}>
                                                                                {/* <Text>{i18n.t('balance')}</Text> */}
                                                                                <Text style={{ fontSize: 14, fontFamily: 'Gotham-Light' }}>{i18n.t('balance')}</Text>
                                                                            </View>
                                                                            <View style={{ flex: 0.7, alignItems: 'center' }}>
                                                                                <Text style={{ fontSize: 14, fontFamily: 'Gotham-Black', color: 'gray' }}>IDR {this.state.balance}</Text>
                                                                            </View>
                                                                        </View>
    
                                                                        <View style={styles.line2}></View>
                                                                        <View style={{ flexDirection: 'row', flex: 1 }}>
                                                                            <View style={{ flex: 0.3, justifyContent: 'center' }}>
                                                                                {/* <Text>{i18n.t('balance')}</Text> */}
                                                                                <Text style={{ fontSize: 14, fontFamily: 'Gotham-Light' }}>{i18n.t('point')}</Text>
                                                                            </View>
                                                                            <View style={{ flex: 0.7, alignItems: 'center' }}>
                                                                                <Text style={{ fontSize: 14, fontFamily: 'Gotham-Black', color: 'gray' }}>IDR {this.state.points}</Text>
                                                                            </View>
                                                                        </View>
                                                                        {
                                                                            this.state.is_expired ? (
                                                                                <TouchableOpacity onPress={() => this.props.navigation.navigate('Renewal')}>
                                                                                    <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', marginRight: 20, marginLeft: 20, marginTop: 20, justifyContent: 'center' }}>
                                                                                        <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 15 }}>RENEWAL</Text>
                                                                                    </View>
                                                                                </TouchableOpacity>
                                                                            ) : null
                                                                        }
                                                                    </Card>
                                                                    {this.state.old_balance_claimed == false ? (
                                                                        <Card style={{ padding: 10, margin: 10, alignContent: 'center' }}>
                                                                            <View style={{ flex: 1, height: 80, borderRadius: 20, marginRight: 10, marginLeft: 10, justifyContent: 'center' }}>
                                                                                {/* <Text style={{ fontSize: 14, fontFamily: 'Gotham-Light', textAlign: 'center', marginBottom: 10 }}>CREDIT : {this.state.old_balance} </Text> */}
                                                                                <NumberFormat decimalScale={0} value={this.state.old_balance} renderText={value => <Text style={{ fontSize: 14, fontFamily: 'Gotham-Light', textAlign: 'center', marginBottom: 10, color: '#838383' }}>CREDIT : Rp. {value}</Text>} displayType={'text'} thousandSeparator={true} prefix={''} />
                                                                                <View style={{ justifyContent: 'center' }}>
                                                                                    <TouchableOpacity onPress={() => this.onClickClaimCredit()}>
                                                                                        <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', marginRight: 20, marginLeft: 20, justifyContent: 'center' }}>
                                                                                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center', margin: 15 }}>CLAIM CREDIT</Text>
                                                                                        </View>
                                                                                    </TouchableOpacity>
                                                                                </View>
                                                                            </View>
                                                                        </Card>) : (null)}
                                                                </>
    
                                                            )
                                                    }
                                                </View>
                                            </View>
                                        </View>
                                        <TouchableOpacity style={styles.submitTopUp} activeOpacity={.5} onPress={() => this.props.navigation.navigate('TopUpInfo')}>
                                            <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center' }}>{i18n.t('topup')}</Text>
                                        </TouchableOpacity>

                                        <View style={{ padding: 10, height: 250, top: 10, margin: 0 }}>
                                            <ImageBackground style={{ width: '100%', height: '100%', padding: 0, margin: 0 }} resizeMode='stretch' source={this.state.img_card ? { uri: this.state.img_card } : null}>
                                                <View style={{ justifyContent: 'center' }}>
                                                    <Text style={{ fontFamily: 'Gotham-Black', margin: 15, fontSize: 14, color: '#c9af6d', top: 170 }}>
                                                        {this.state.card_number}
                                                    </Text>
                                                </View>
                                            </ImageBackground>
                                        </View>

                                        <View style={{ marginLeft: 10, marginRight: 10, padding: 5 }}>
                                            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', margin: 5 }}>
                                                <TouchableOpacity style={{ marginBottom: 5, margin: 3 }} onPress={() => this.TransferBalance()} >
                                                    <Card style={{ height: 120, width: 155 }}>
                                                        <View style={{ height: 50, alignItems: 'center', padding: 10, flex: 1 }}>
                                                            <Image
                                                                style={{ height: 50, width: 50, justifyContent: 'center' }}
                                                                source={require('../assets/icon/4.png')}
                                                            />
                                                            <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', top: 5, fontSize: 14, color: '#838383' }}> {i18n.t('Transferbalance')}</Text>
                                                        </View>
                                                    </Card>
                                                </TouchableOpacity>
                                                <View style={{ width: 5 }}></View>
                                                <TouchableOpacity style={{ marginBottom: 5, margin: 3 }} onPress={() => this.handleuseBalance()}>
                                                    <Card style={{ height: 120, width: 155 }}>
                                                        <View style={{ height: 50, alignItems: 'center', padding: 10, flex: 1 }}>
                                                            <Image
                                                                style={{ height: 50, width: 50, justifyContent: 'center' }}
                                                                source={require('../assets/icon/2.png')}
                                                            />
                                                            <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', top: 5, fontSize: 14, color: '#838383' }}> {i18n.t('Usebalancepoint')}</Text>
                                                        </View>
                                                    </Card>
                                                </TouchableOpacity>
                                            </View>
                                            <View style={{ flex: 1, flexDirection: 'row', marginBottom: 10, justifyContent: 'center' }}>
    
                                                <TouchableOpacity style={{ marginBottom: 5, margin: 4 }} onPress={() => this.props.navigation.navigate('Transaction History')} >
                                                    <Card style={{ height: 120, width: 155 }}>
                                                        <View style={{ height: 50, alignItems: 'center', padding: 10, flex: 1 }}>
                                                            <Image
                                                                style={{ height: 50, width: 50, justifyContent: 'center' }}
                                                                source={require('../assets/icon/1.png')}
                                                            />
                                                            <Text style={{ fontFamily: 'Gotham-Black', flexDirection: 'row', textAlign: 'center', flexWrap: 'wrap', margin: 5, color: '#838383' }}> {i18n.t('Transactionhistory')}</Text>
                                                        </View>
                                                    </Card>
                                                </TouchableOpacity>
                                                <View style={{ width: 5 }}></View>
                                                <TouchableOpacity style={{ marginBottom: 5, margin: 4 }} onPress={() => this.props.navigation.navigate('Renewal')}>
                                                    <Card style={{ height: 120, width: 155 }}>
    
                                                        <View style={{ height: 50, alignItems: 'center', padding: 10, flex: 1 }}>
                                                            <Image
                                                                style={{ height: 50, width: 50, justifyContent: 'center' }}
                                                                source={require('../assets/icon/3.png')}
                                                            />
                                                            <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', top: 5, fontSize: 14, margin: 5, color: '#838383' }}> {i18n.t('Renewal')}</Text>
                                                        </View>
                                                    </Card>
                                                </TouchableOpacity>
                                            </View>
                                            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', display: 'none' }}>
                                                {this.state.premium === false ? (
                                                    <TouchableOpacity onPress={() => this.props.navigation.navigate('Upgrade Premium')} style={{ marginBottom: 20, marginRight: 5, marginLeft: 5 }}>
                                                        <Card style={{ width: 200, paddingHorizontal: 10, paddingTop: 20, paddingBottom: 20 }}>
                                                            <View style={{ flex: 1, alignItems: 'center' }}>
                                                                <MaterialIcons name="autorenew" size={30} color="gray" style={{ marginBottom: 10 }} />
                                                                <Text style={{ fontFamily: 'Gotham-Black', textAlign: 'center', fontSize: 14, color: '#838383' }}>{i18n.t('upgradePremium')}</Text>
                                                            </View>
                                                        </Card>
                                                    </TouchableOpacity>
                                                ) : (
                                                        null
                                                    )}
                                            </View>
                                        </View>
    
                                        <View style={{ flex: 1 }}>
                                            <TouchableOpacity onPress={() => this.logout()}>
                                                <View style={{ height: 40, borderRadius: 10, backgroundColor: '#CFB368', justifyContent: 'center', marginLeft: 20, marginRight: 20, marginBottom: 20, padding: 5, bottom: 5, top: 1 }}>
                                                    <Text style={{ fontFamily: 'Gotham-Black', color: 'white', fontSize: 16, textAlign: 'center' }}>{i18n.t('logout')}</Text>
                                                </View>
                                            </TouchableOpacity>
    
                                        </View>
                                    </View>
                                )
                        }
    
                        <View style={{ flex: 1, marginBottom: 20, marginTop: 25 }}>
                            <Text style={{ color: 'grey', fontSize: 12, textAlign: 'center' }}>Version {Constants.manifest.version} Build {Constants.manifest.extra.buildNumber}</Text>
                            <Text style={{ color: 'grey', fontSize: 12, textAlign: 'center' }}>{Constants.manifest.extra.remarks}</Text>
                        </View>
                    </ScrollView>
    
                </View >
            ) 
        } catch (error) {
            Alert.alert('Error : ' + error)
        }
        
    }
}

Account.navigationOptions = {
    header: null,
};

const styles = StyleSheet.create({

    container: {
        flex: 1,
        backgroundColor: 'white',
        alignItems: 'stretch',
    },
    profil: {
        height: 150,
        backgroundColor: 'white',
        alignItems: 'center',
        top: 40,
    },

    Card: {
        top: 50,
        alignItems: 'center',
        alignContent: 'center',
        marginRight: 10,
        marginLeft: 10,
    },

    card: {
        top: 5,
        flex: 1,
        alignItems: 'center',
        marginRight: 10,
        marginLeft: 10,
    },

    line: {
        top: 3,
        borderRadius: 1,
        borderColor: 'black',
        borderWidth: 1,
        width: "100%",
        height: 1,
        bottom: 5,

    },
    line1: {
        top: 3,
        borderRadius: 1,
        borderColor: 'black',
        borderWidth: 1,
        width: "100%",
        height: 1,
        bottom: 5,

    },

    imgBackground: {
        width: '100%',
        height: '100%',
        flex: 1
    },
    submitTopUp: {
        marginTop: 70,
        top: 10,
        height: 40,
        marginLeft: 20,
        justifyContent: 'center',
        marginRight: 20,
        backgroundColor: '#c9af6d',
        borderRadius: 10,
        borderWidth: 0,
        borderColor: '#fff',
        textAlign: 'center',
    },
    logo: {
        alignSelf: 'flex-start',
        marginTop: 70,
        width: 290,
        height: 290,
        bottom: 145,

    },
    v_logo: {
        flex: 2,
        flexDirection: 'column-reverse',
        alignContent: 'flex-start',
    },

    line: {
        borderBottomColor: '#c9af6d',
        borderBottomWidth: 2,
        alignSelf: 'stretch',
        width: "100%",
        height: 10,
        bottom: 5,
    },
    line2: {
        borderBottomColor: '#c9af6d',
        borderBottomWidth: 1,
        alignSelf: 'stretch',
        width: "100%",
        height: 10,
        bottom: 5,
    },
})

//subscribe
const mapStateToProps = (state) => {
    return {
        session_id: state.session_id,
        set_card: state.set_card,
        in_payment: state.in_payment,
        language: state.language,
        BASE_URL: state.BASE_URL,
    }
}

const mapDispatchToProps = (dispacth) => {
    return {
        setConfig: (configProps) => dispacth({
            type: ActionType.SET_LOGOUT,
            data: {
                session_id: configProps.session_id
            }
        }),
        setCardactive: (cardProps) => dispacth({

            type: ActionType.SET_CARD,
            data: {
                set_card: cardProps.set_card,
            }
        }),
        setCardNumber: (setCardNumberProps) => dispacth({

            type: ActionType.SET_ACCOUNT_NUMBER,
            data: {
                card_number: setCardNumberProps.card_number,
            }
        }),
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Account);

