import React, { Component } from 'react';
import {
    Alert,
    Dimensions,
    KeyboardAvoidingView,
    Platform,
    ScrollView,
    StyleSheet,
    View,
} from 'react-native';
import { connect } from 'react-redux';
import * as Utils from '../../../utils/UtilsFunction';
import { Color } from '../../../config/Color';
import I18n from 'react-native-i18n';
import { ScreenComponent } from '../../../components/ScreenComponent';
import {
    fetchActivePaySubscription,
    fetchActivePaySubscriptionReset,
    fetchGetSubscriptionList,
    fetchGetSubscriptionListReset,
} from '../../../redux/insurance/insurance.actions';
import DropdownAlert from 'react-native-dropdownalert';
import { readUser } from '../../../webservice/AuthApi';
import * as Animatable from 'react-native-animatable';
import { createStructuredSelector } from 'reselect';
import {
    selectActivatePaySubscription,
    selectSubscriptionList,
} from '../../../redux/insurance/insurance.selector';
import { responsiveWidth } from 'react-native-responsive-dimensions';
import { Dropdown } from 'react-native-material-dropdown-v2';
import { store } from '../../../redux/store';

const { width, height } = Dimensions.get('window');
const CIRCLE_SIZE = width * 0.5;

class SelectAssurance extends Component {
    constructor(props) {
        super(props);
        this.state = {
            user: null,
            subscriptions: [],
            subscription: null,
            
            wallet: store.getState().walletDetailReducer.result.response,
        };
        //this.props.onSelectSubscription(selectedSubscription);
        this.dropDownAlertRef = React.createRef();
        this.subscriptionRef = React.createRef();
    }

    // onSelectSubscription = (selectedSubscription) => {
    //     this.setState.(selectedSubscription)
    // }

    componentDidMount() {
        readUser().then((user) => {
            this.setState({ user });
        });
        // this.props.fetchGetSubscriptionListReset();
        // this.props.fetchActivePaySubscriptionReset();
    }

    componentDidUpdate(prevProps, prevState) {
        
        if (this.state.user !== prevState.user) {
            if (this.state.user !== null) {
                this.props.fetchGetSubscriptionList(
                    this.state.user.id,
                    'UNPAID',
                    true
                );
            }
        }

        if (this.props.subscriptionList.result !== prevProps.subscriptionList.result) {
            const subscriptionListTemp = this.props.subscriptionList.result.response;
            this.setState({ subscriptions: subscriptionListTemp });
        }

        if (this.props.subscriptionList.error !== prevProps.subscriptionList.error) {
            Alert.alert(
                I18n.t('ERROR_LABLE'),
                Utils.getErrorMsg(this.props.subscriptionList),
                [
                    {
                        text: I18n.t('OK'),
                        onPress: () => {
                            this.props.fetchGetSubscriptionListReset();
                        },
                    },
                ],
                { cancelable: false }
            );
        }
    }

    render() {
        
        return (
            <ScreenComponent>
                <DropdownAlert ref={this.dropDownAlertRef} />
                <KeyboardAvoidingView
                    behavior={Platform.OS === 'android' ? 'height' : 'padding'}
                    style={{ flex: 1 }}
                >
                    <View style={styles.container}>
                        <Animatable.View
                            ref={(comp) => {
                                this.subscriptionRef = comp;
                            }}
                            style={{
                                width: responsiveWidth(90),
                                height: 60,
                                alignSelf: 'center',
                                borderRadius: 10,
                                paddingLeft: 20,
                                paddingRight: 20,
                                backgroundColor: 'white',
                            }}
                        >
                            <Dropdown
                                label={I18n.t('SELECT_INSURANCE')}
                                data={this.state.subscriptions}
                                useNativeDriver={true}
                                onChangeText={(value, index, data) => {
                                    console.log('Value', value);
                                    this.props.onSelectSubscription(value)
                                    this.setState({
                                        subscription: {
                                            id: value.id,
                                            insurance_subscription_id: value.insurance_subscription_id,
                                            network_id: value.network_id,
                                            user_id: value.user_id,
                                            number_of_months: value.number_of_months,
                                            bonus_amount: value.bonus_amount,
                                            number_of_beneficiaries: value.number_of_beneficiaries,
                                            total_bonus_amount: value.total_bonus_amount,
                                            state: value.state,
                                            created_at: value.created_at,
                                            updated_at: value.updated_at,
                                            start_at: value.start_at,
                                            end_at: value.end_at,
                                            reason: value.reason,
                                            network: value.network,
                                            beneficiaries: value.beneficiaries,
                                        },
                                    });
                                }}
                                valueExtractor={(value) => {
                                    return value;
                                }}
                                labelExtractor={(value) => {
                                    return `${I18n.t('MNT')}: ${
                                        value.amount
                                    } | ${I18n.t('FACT')}: ${value.invoice_id.slice(
                                        0,
                                        7
                                    )} | ${I18n.t('RESTE')}: ${
                                        value.remaining_amount
                                    }`;
                                }}
                            />
                        </Animatable.View>
                    </View>
                </KeyboardAvoidingView>
            </ScreenComponent>
        );
    }
}

const mapStateToProps = createStructuredSelector({
    subscriptionList: selectSubscriptionList,
    activatePaySubscription: selectActivatePaySubscription,
});

export default connect(mapStateToProps, {
    fetchActivePaySubscription,
    fetchGetSubscriptionList,
})(SelectAssurance);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Color.primaryDarkColor,
    },
    btnvalide: {
        marginTop: 20,
    marginLeft: 20,
    marginRight: 20,
    borderColor: 'transparent',
    backgroundColor: Color.accentLightColor,
    height: 52
},

    contain: {
        alignItems: 'center',
        marginTop: 40,
        paddingBottom: 20,
        paddingLeft: 20,
        paddingRight: 20,
        flex: 1,
    },
  
});
