import React from 'react';
import {
    View,
    StyleSheet,
    Text,
    StatusBar,
    Image,
    ScrollView,
    TouchableOpacity,
    Alert,
    Button
} from 'react-native';

import { StackActions } from '@react-navigation/native';
import { connect } from 'react-redux';
import { Card } from 'react-native-shadow-cards';
import ActionType from '../redux/globalActionType';
import { CommonActions } from '@react-navigation/native';
import { Ionicons, MaterialIcons, AntDesign, FontAwesome } from '@expo/vector-icons';
import Axios from 'axios';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import * as Device from 'expo-device';
import session from '../function/session';

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
        }
    }

    componentDidMount() {

        this._getProfile()
        this._unsubscribe = this.props.navigation.addListener('focus', () => {
            this._getProfile()
        });
    }

    componentWillUnmount() {
        this._unsubscribe();
    }

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

            Alert.alert('Silahkan anda coba di real Device')
        } else {
            this._getCurrentPosisition()
        }
    }
    _getCurrentPosisition = async () => {
        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()
    }

    logout() {

        let configProps = {
            session_id: ''
        }
        this.props.setConfig(configProps);
        this.props.navigation.replace('Login');
    }

    _getProfile() {
        let params = {
            session_id: this.props.session_id,
            lat: this.state.my_lat,
            long: this.state.my_long,
            closest_outlet: 1
        }

        Axios.post('https://excelsocrm.ravintoladev.com/crm/v2/member/get_profile', params).then(res => {
            // console.log('WAKWAWWWW ' + JSON.stringify(res.data))
            const dataCard = res.data
            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

            if (kaspro === "") {

                let cardProps = {
                    set_card: false

                }

                this.props.setCardactive(cardProps)
            } else {
                let cardProps = {
                    set_card: true
                }
                this.props.setCardactive(cardProps)
            }

            let account_number = dataCard.kaspro_account_number

            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,
            })

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

    TransferBalance() {

        if (this.state.premium === false) {
            Alert.alert(
                'Akun Belum Premium',
                'Apakah anda ingin Upgrade Premium ?',

                [{ text: 'Cancel' },
                { text: 'OK', onPress: () => this.props.navigation.navigate('Upgrade Premium') }
                ]
            )
        } else {
            this.props.navigation.navigate('Transfer Balance');
        }
    }


    render() {
        const navigation = this.props.navigation
        return (
            <View style={styles.container}>
                <ScrollView>
                    <View style={styles.profil}>
                        <Image
                            style={{ height: 70, width: 70, top: 15, }}
                            source={require('../assets/images/user.png')}
                        />
                        <Text style={styles.txtNama}>
                            {this.props.username}
                        </Text>
                        <Text style={styles.txtEmail}>
                            {this.state.email} {this.props.set_card}
                        </Text>
                    </View>
                    {
                        this.props.set_card === false ? (
                            <View>
                                <View style={styles.Card}>
                                    {/* <Card style={{ padding: 10, margin: 10, alignContent: 'center' }}>

                                        <Text style={{ textAlign: "center", fontSize: 40, color: '#c9af6d' }}>
                                        </Text>
                                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}> {'\n'}

                                        </Text>
                                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>{'\n'}

                                        </Text>
                                    </Card>

                                    <Card style={{ padding: 10, margin: 10, alignContent: 'center' }}>

                                        <Text style={{ textAlign: "center", fontSize: 40, color: '#c9af6d' }}>
                                        </Text>
                                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}> {'\n'}

                                        </Text>
                                        <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>{'\n'}

                                        </Text>
                                    </Card> */}
                                </View>
                                <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
                                    <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile')} style={{ marginBottom: 10 }}>
                                        <Card style={{ height: 100, width: 160 }}>
                                            <View style={{ height: 50, alignItems: 'center' }}>
                                                <MaterialIcons name="monetization-on" size={30} color="gray" style={{ top: 20 }} />
                                                <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>PROFIL</Text>
                                            </View>
                                        </Card>
                                    </TouchableOpacity>
                                    <View style={{ width: 5 }}></View>
                                    <TouchableOpacity onPress={() => this.props.navigation.navigate('Card Activation')}>
                                        <Card style={{ height: 100, width: 160 }}>
                                            <View style={{ height: 50, alignItems: 'center' }}>
                                                <AntDesign name="shoppingcart" size={30} color="gray" style={{ top: 20 }} />
                                                <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>ACTIVATION CARD</Text>
                                            </View>
                                        </Card>
                                    </TouchableOpacity>
                                </View>
                                <View style={{ flex: 1, margin: 40 }}>
                                    <Button
                                        title="Logout"
                                        onPress={() => this.logout()}
                                    />
                                </View>
                            </View>
                        ) : (
                                <View>
                                    <View style={styles.Card}>
                                        <Card style={{ padding: 10, margin: 10, alignContent: 'center' }}>
                                            <Text>
                                                YOUR CARD NUMBER | {this.state.expire_date}{'\n'}
                                            </Text>
                                            <Text style={{ textAlign: "center", fontSize: 40, color: '#c9af6d' }}>
                                                {this.state.account_number}
                                            </Text>
                                            <View style={styles.line}></View>
                                            <Text style={{ textAlign: 'left', fontWeight: 'bold' }}> {'\n'}
                                            BALANCE: {this.state.balance}{'\n'}
                                            </Text>
                                            <View style={styles.line}></View>
                                            <Text style={{ textAlign: 'left', fontWeight: 'bold' }}>{'\n'}
                                            POINTS: {this.state.points}
                                            </Text>
                                        </Card>
                                    </View>
                                    <TouchableOpacity style={styles.submitTopUp} activeOpacity={.5} onPress={() => this.props.navigation.navigate('TopUpInfo')}>
                                        <Text style={{ color: '#fff', textAlign: 'center' }}>TOP UP BALANCE</Text>
                                    </TouchableOpacity>
                                    <View style={{ padding: 10, margin: 10, height: 200 }}>
                                        <Image style={{ width: '100%', height: '100%', padding: 0, margin: 0 }} resizeMode='stretch' source={this.state.img_card ? { uri: this.state.img_card } : null} />
                                    </View>
                                    <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
                                        <TouchableOpacity style={{ marginBottom: 10 }} onPress={() => this.TransferBalance()} >
                                            <Card style={{ height: 100, width: 160 }}>

                                                <View style={{ height: 50, alignItems: 'center' }}>
                                                    <MaterialIcons name="monetization-on" size={30} color="gray" style={{ top: 20 }} />
                                                    <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>TRANSFER BALANCE</Text>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                        <View style={{ width: 5 }}></View>
                                        <TouchableOpacity>
                                            <Card style={{ height: 100, width: 160 }}>
                                                <View style={{ height: 50, alignItems: 'center' }}>
                                                    <AntDesign name="shoppingcart" size={30} color="gray" style={{ top: 20 }} />
                                                    <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>USE BALANCE</Text>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                    </View>
                                    <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', top: 10 }}>
                                        <TouchableOpacity onPress={() => this.props.navigation.navigate('Renewal')} style={{ marginBottom: 20 }}>
                                            <Card style={{ height: 100, width: 160 }}>
                                                <View style={{ height: 50, alignItems: 'center' }}>
                                                    <MaterialIcons name="autorenew" size={30} color="gray" style={{ top: 20 }} />
                                                    <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>RENEWAL</Text>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                        <TouchableOpacity onPress={() => this.props.navigation.navigate('Transaction History')} style={{ marginBottom: 20, marginRight: 5, marginLeft: 5 }}>
                                            <Card style={{ height: 100, width: 160 }}>
                                                <View style={{ height: 50, alignItems: 'center' }}>
                                                    <MaterialIcons name="autorenew" size={30} color="gray" style={{ top: 20 }} />
                                                    <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>TRANSACTION HISTORY</Text>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                    </View>
                                    <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', top: 10 }}>
                                        {this.state.premium === false ? (
                                            <TouchableOpacity onPress={() => this.props.navigation.navigate('Upgrade Premium')} style={{ marginBottom: 20, marginRight: 5, marginLeft: 5 }}>
                                                <Card style={{ height: 100, width: 160 }}>
                                                    <View style={{ height: 50, alignItems: 'center' }}>
                                                        <MaterialIcons name="autorenew" size={30} color="gray" style={{ top: 20 }} />
                                                        <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>UPGRADE PREMIUM</Text>
                                                    </View>
                                                </Card>
                                            </TouchableOpacity>
                                        ) : (
                                                null
                                            )}
                                        <TouchableOpacity onPress={() => this.props.navigation.navigate('Profile')} style={{ marginBottom: 10 }}>
                                            <Card style={{ height: 100, width: 160 }}>
                                                <View style={{ height: 50, alignItems: 'center' }}>
                                                    <MaterialIcons name="monetization-on" size={30} color="gray" style={{ top: 20 }} />
                                                    <Text style={{ textAlign: 'center', top: 30, fontSize: 14 }}>PROFIL</Text>
                                                </View>
                                            </Card>
                                        </TouchableOpacity>
                                    </View>
                                    <View style={{ flex: 1, margin: 40 }}>
                                        <Button
                                            title="Logout"
                                            onPress={() => this.logout()}
                                        />
                                    </View>
                                </View>
                            )
                    }
                </ScrollView>
            </View>
        )
    }
}

Account.navigationOptions = {
    header: null,
};

const styles = StyleSheet.create({

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

    Card: {
        alignItems: 'center',
        backgroundColor: 'white',
        alignContent: 'center',
    },

    line: {
        borderBottomColor: "black",
        borderBottomWidth: StyleSheet.hairlineWidth,
        alignSelf: 'stretch',
        width: "100%",
        height: 3,
        bottom: 5,
    },

    imgBackground: {
        width: '100%',
        height: '100%',
        flex: 1
    },
    submitTopUp: {
        marginTop: 10,
        paddingTop: 15,
        paddingBottom: 15,
        marginLeft: 15,
        marginRight: 15,
        backgroundColor: '#c9af6d',
        borderRadius: 10,
        borderWidth: 0,
        borderColor: '#fff',
        textAlign: 'center',
    },
})

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

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,
            }
        }),
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Account);
