import React, {useEffect, useState} from 'react';
import {
    Alert,
    Dimensions,
    FlatList,
    KeyboardAvoidingView,
    Platform,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    View,
} from 'react-native';
import {connect, useDispatch} from 'react-redux';
import Modal from 'react-native-modal';
import {Formik} from 'formik';
import * as Yup from 'yup';
import * as Utils from '../../../utils/UtilsFunction';
import {displayToast} from '../../../utils/UtilsFunction';
import {Color} from "../../../config/Color";
import I18n from 'react-native-i18n';
import {ScreenComponent} from "../../../components/ScreenComponent";
import Text from '../../../components/Text';
import PasswordInput from '../../../components/PasswordInput';
import Button from "../../../components/Button";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import {responsiveWidth} from "react-native-responsive-dimensions";
import {
    fetchAddBeneficiaryToSubscription,
    fetchAddBeneficiaryToSubscriptionReset,
    fetchDeleteBeneficiary,
    fetchDeleteBeneficiaryReset,
    fetchGetInsurancePrimeAmount,
    fetchGetListInsurance,
    fetchGetListInsuranceReset,
    fetchGetSubscriptionList,
    fetchGetSubscriptionListReset,
    fetchSubscribeInsurance,
    fetchUploadInsurance
} 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 {
    selectAddBeneficiaryToSubscription,
    selectDeleteBeneficiary,
    selectInsuranceList,
    selectInsurancePrimeAmount,
    selectSubscribeInsurance,
    selectSubscriptionList,
    selectUploadInsuranceImages
} from "../../../redux/insurance/insurance.selector";

import {Dropdown} from "react-native-material-dropdown-v2";
import Icon from "react-native-vector-icons/FontAwesome5";
import {store} from "../../../redux/store";

let moment = require('moment-timezone');

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

const styles = StyleSheet.create({
    textInput: {
        height: 46,
        backgroundColor: Color.fieldColor,
        borderRadius: 5,
        marginTop: 10,
        padding: 10,
        width: '100%',
    },
    lineRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingBottom: 20,
    },
    contain: {
        alignItems: 'center',
        marginTop: 40,
        paddingBottom: 20,
        paddingLeft: 20,
        paddingRight: 20,
        flex: 1,
    },
    circle: {
        width: CIRCLE_SIZE,
        height: CIRCLE_SIZE,
        borderRadius: CIRCLE_SIZE / 2,
        position: 'absolute',
        top: '15%',
    },
    circleContainer: {
        alignItems: 'flex-end',
        right: -(CIRCLE_SIZE / 3),
        top: -(CIRCLE_SIZE / 1.5),
    },
    lineSeparator: {
        borderWidth: 1,
        width: '40%',
        height: 1,
        alignSelf: 'center',
    },
    line: {
        width: 1,
        height: 14,
        backgroundColor: Color.grayColor,
        marginLeft: 10,
    },
    contentModeView: {
        width: 30,
        height: '100%',
        alignItems: 'flex-end',
        justifyContent: 'center',
    },
    contentFilter: {
        flexDirection: 'row',
        alignItems: 'center',
        marginLeft: 10,
    },
    bottomModal: {
        justifyContent: 'flex-end',
        margin: 0,
    },
    contentFilterBottom: {
        width: "100%",
        borderTopLeftRadius: 8,
        borderTopRightRadius: 8,
        paddingHorizontal: 20
    },
    contentSwipeDown: {
        paddingTop: 10,
        alignItems: 'center',
    },
    lineSwipeDown: {
        width: 30,
        height: 2.5,
        backgroundColor: Color.dividerColor,
    },
    contentActionModalBottom: {
        flexDirection: 'row',
        paddingVertical: 15,
        justifyContent: 'space-between',
        borderBottomWidth: 1,
    },
    containModal: {
        paddingVertical: 10,
        paddingHorizontal: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    floatingButtonAdd: {
        backgroundColor: Color.accentColor,
        position: "absolute",
        width: 25,
        bottom: 0,
        zIndex: 1000,
        right: 20,
        top: 35,
        height: 25,
        borderRadius: 12.5,
        alignItems: 'center',
        justifyContent: 'center',
    },
    contentSwitch: {
        width: responsiveWidth(40),
    },
    switch: {},
    choosePhotoBtn: {
        marginTop: 10,
        marginBottom: 10,
        width: "auto",
        height: "auto",
        padding: 5,
        alignItems: 'center',
        borderColor: Color.borderColor,
        marginRight: 10,
        elevation: 2,
    },
    checkbox: {
        alignSelf: "center",
        color: "white"
    },
    itemAmountPerMonth: {
        paddingLeft: 10,
        marginTop: 10,
        flexDirection: 'row',
    },
    dot: {
        width: 12,
        height: 12,
        borderRadius: 6
    },
    blockView: {
        paddingVertical: 10,
        borderBottomWidth: 0.5,
    },
});

const DeleteBeneficiaryScreen = ({
                                     fetchAddBeneficiaryToSubscription,
                                     addBeneficiaryToSubscription,
                                     fetchGetSubscriptionList,
                                     fetchDeleteBeneficiary,
                                     subscriptionList,
                                     deleteBeneficiary,
                                     navigation
                                 }) => {

    const [user, setUser] = useState(null);
    const [insurance, setInsurance] = useState(null);
    const [password, setPassword] = useState(null);
    const dispatch = useDispatch();
    const [wallet] = useState(store.getState().walletDetailReducer.result.response);

    const [modalViewBeneficiariesVisible, setModalViewBeneficiariesVisible] = useState(false);
    const [subscription, setSubscription] = useState(null);
    const [subscriptions, setSubscriptions] = useState([]);
    const [beneficiaries, setBeneficiaries] = useState([]);
    const [beneficiariesToDelete, setBeneficiariesToDelete] = useState([]);


    let subscriptionRef = null;

    useEffect(() => {
        readUser().then((user) => {
            console.log("user", user);
            setUser(user)
        });
        dispatch(fetchAddBeneficiaryToSubscriptionReset());
        dispatch(fetchGetSubscriptionListReset());
    }, []);

    useEffect(() => {
        if (user !== null)
            fetchGetSubscriptionList(user.id, 'EDITABLE', false);
    }, [user]);
    let dropDownAlertRef: any = null;

    useEffect(() => {
        if (subscriptionList.result !== null) {
            let subscriptionListTemp = [];
            subscriptionList.result.response.map((insuranceItem, index) => {
                subscriptionListTemp.push(insuranceItem);
            });
            setSubscriptions(subscriptionListTemp);
        }

        if (subscriptionList.error) {
            Alert.alert(
                I18n.t("ERROR_LABLE"),
                Utils.getErrorMsg(subscriptionList),
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchGetListInsuranceReset());
                        }
                    }
                ],
                {cancelable: false}
            );
            /*            dropDownAlertRef.alertWithType(
                            'error',
                            I18n.t('ERROR_LABEL'),
                            Utils.getErrorMsg(subscriptionList),
                        );
                        dispatch(fetchGetListInsuranceReset());*/
        }
    }, [subscriptionList]);

    useEffect(() => {
        if (deleteBeneficiary.result !== null) {
            Alert.alert(
                I18n.t("SUCCESS"),
                deleteBeneficiary.result.response,
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchDeleteBeneficiaryReset());
                            navigation.goBack();
                        }
                    }

                ],
                {cancelable: false}
            )
        }

        if (deleteBeneficiary.error) {
            Alert.alert(
                I18n.t("ERROR_LABLE"),
                Utils.getErrorMsg(deleteBeneficiary),
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchDeleteBeneficiaryReset());
                        }
                    }
                ],
                {cancelable: false}
            );
            /*            dropDownAlertRef.alertWithType(
                            'error',
                            I18n.t('ERROR_LABEL'),
                            Utils.getErrorMsg(deleteBeneficiary),
                        );
                        dispatch(fetchDeleteBeneficiaryReset());*/
        }
    }, [deleteBeneficiary]);


    const RegisterSchema = Yup.object().shape({
        password:Yup.string().required(I18n.t('THIS_FIELD_IS_REQUIRED'))
    });

    const renderModalViewBeneficiaries = () => {
        return (
            <Modal
                isVisible={modalViewBeneficiariesVisible}
                onSwipeComplete={() => setModalViewBeneficiariesVisible(false)}
                swipeDirection={['down']}
                style={styles.bottomModal}>
                <View
                    style={[styles.contentFilterBottom, {backgroundColor: Color.cardBackgroundColor}]}>
                    <View style={styles.contentSwipeDown}>
                        <View style={styles.lineSwipeDown}/>
                    </View>
                    <View
                        style={[
                            styles.contentActionModalBottom,
                            {borderBottomColor: Color.borderColor},
                        ]}/>
                    <View style={[{marginBottom: 40}]}>
                        <FlatList
                            data={beneficiaries}
                            extraData={beneficiaries}
                            keyExtractor={(item, index) => index}
                            ListEmptyComponent={() => {
                                return (
                                    <Text>{I18n.t('NO_WALLET_HISTORY')}</Text>
                                )
                            }}
                            renderItem={({item, index}) => {
                                console.log("Item", item);
                                return (
                                    <View style={styles.lineRow}>
                                        <View style={{alignItems: 'flex-start'}}>
                                            <Text body1>{I18n.t('NOM_ASSURE')}</Text>
                                            <Text caption1 grayColor>
                                                {`${item.firstname} ${item.lastname}`}
                                            </Text>
                                        </View>
                                        <View style={{alignItems: 'flex-start'}}>
                                            <Text body1>{I18n.t('AFFILIATION')}</Text>
                                            <Text caption1 grayColor>
                                                {item.affiliation === 'CHILD' ? I18n.t('ENFANT') : I18n.t('CONJOINT')}
                                            </Text>
                                        </View>
                                        <View style={styles.iconRight}>
                                            <TouchableOpacity
                                                onPress={() => {

                                                    Alert.alert(
                                                        I18n.t("TITLE_SUPPRESS_CONFIRM"),
                                                        I18n.t("TEXT_SUPPRESS_CONFIRM_BENEFICIARY"),
                                                        [
                                                            {
                                                                text: I18n.t("OK"), onPress: () => {
                                                                    setBeneficiariesToDelete([...beneficiariesToDelete, item.id]);
                                                                    setBeneficiaries(beneficiaries.filter(beneficiary => beneficiary.id !== item.id));
                                                                }
                                                            },
                                                            {
                                                                text: I18n.t("CANCEL_LABEL"), onPress: () => {

                                                                }
                                                            }
                                                        ],
                                                        {cancelable: false}
                                                    )
                                                }}>
                                                <Icon
                                                    name="minus-circle"
                                                    size={24}
                                                    color={Color.grayColor}
                                                />
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                );
                            }}/>
                    </View>

                    <Button
                        style={{marginTop: 20, marginBottom: 20}}
                        full
                        onPress={() => {
                            if (beneficiaries.length >= 1 && beneficiariesToDelete.length > 0)
                                displayToast(I18n.t('ENTER_PASSWORD_TO_VALID_MODIFICATION'));

                            setModalViewBeneficiariesVisible(false)
                        }}>
                        {I18n.t('OK')}
                    </Button>
                </View>
            </Modal>
        );
    };


    return (
        <ScreenComponent>
            <DropdownAlert ref={ref => (dropDownAlertRef = ref)}/>
            <KeyboardAvoidingView
                behavior={Platform.OS === 'android' ? 'height' : 'padding'}
                style={{flex: 1}}>

                <ScrollView style={{flex: 1}}>
                    <Formik validationSchema={RegisterSchema}
                            initialValues={{
                                password: '',
                            }}
                            onSubmit={(values) => {
                                if (user !== null) {
                                    if (subscription === null) {
                                        subscriptionRef.shake(800);
                                    } else {
                                        console.log(user);
                                        console.log("insurance", insurance);
                                        setPassword(values.password);
                                        fetchDeleteBeneficiary(subscription.id, {
                                            password: values.password,
                                            beneficiaries_ids: beneficiariesToDelete
                                        });
                                    }
                                }
                            }}>

                        {({
                              values,
                              errors,
                              touched,
                              handleChange,
                              handleBlur,
                              handleSubmit,
                              isSubmitting,
                          }) => (
                            <View style={styles.contain}>

                                <Animatable.View ref={(comp) => {
                                    subscriptionRef = comp
                                }}
                                                 style={{
                                                     width: responsiveWidth(90),
                                                     height: 60,
                                                     alignSelf: 'center',
                                                     borderRadius: 10,
                                                     paddingLeft: 20,
                                                     paddingRight: 20,
                                                     backgroundColor: 'white'
                                                 }}>
                                    <Dropdown
                                        label={I18n.t('SELECT_SUBSCRIPTION')}
                                        data={subscriptions}
                                        useNativeDriver={true}
                                        onChangeText={(value, index, data) => {
                                            console.log("Value", value);
                                            setBeneficiaries(value.beneficiaries);
                                            setSubscription(
                                                {
                                                    id: value.id,
                                                    insured_id: value.insured_id,
                                                    subscription: value.subscription,
                                                    beneficiaries: value.beneficiaries
                                                }
                                            );
                                            setModalViewBeneficiariesVisible(true);
                                        }}
                                        valueExtractor={(value) => {
                                            return value
                                        }}
                                        labelExtractor={(value) => {
                                            return `${value.network.name} | ${I18n.t('ETAT')}: ${value.state} | ${I18n.t('AMOUNT_LABEL')}: ${value.total_bonus_amount}`
                                        }}
                                    />
                                </Animatable.View>

                                <PasswordInput
                                    style={{marginTop: 10}}
                                    onChangeText={handleChange('password')}
                                    placeholder={I18n.t('PASSWORD')}
                                    secureTextEntry
                                    icon={<FontAwesome name="lock" size={20}/>}
                                    value={values.password}
                                    onBlur={handleBlur('password')}
                                    success={touched.password && !errors.password}
                                    touched={touched.password}
                                    error={errors.password}
                                />

                                <Button
                                    style={{marginTop: 20}}
                                    full
                                    loading={deleteBeneficiary.loading}
                                    onPress={handleSubmit}>
                                    {I18n.t('SUBMIT_LABEL')}
                                </Button>
                            </View>
                        )}
                    </Formik>

                </ScrollView>
            </KeyboardAvoidingView>
            {modalViewBeneficiariesVisible && renderModalViewBeneficiaries()}
            {(subscription !== null) && (<TouchableOpacity
                style={{
                    alignItems: 'center',
                    flexDirection: 'row',
                    width: 60,
                    position: 'absolute',
                    bottom: 10,
                    right: 10,
                    height: 60,
                    padding: 3,
                    backgroundColor: Color.primaryColor,
                    borderRadius: 100,
                }}
                onPress={() => setModalViewBeneficiariesVisible(true)}
            >
                <Text whiteColor title2>{beneficiaries.length}</Text>
                <Text whiteColor caption2>{I18n.t('AYANT_DROIT')}</Text>
            </TouchableOpacity>)}
        </ScreenComponent>
    );
};

const mapStateToProps = createStructuredSelector({
    insuranceList: selectInsuranceList,
    subscribeInsurance: selectSubscribeInsurance,
    uploadInsuranceImages: selectUploadInsuranceImages,
    insurancePrimeAmount: selectInsurancePrimeAmount,
    addBeneficiaryToSubscription: selectAddBeneficiaryToSubscription,
    subscriptionList: selectSubscriptionList,
    deleteBeneficiary: selectDeleteBeneficiary
});

export default connect(mapStateToProps, {
    fetchGetListInsurance,
    fetchSubscribeInsurance,
    fetchGetInsurancePrimeAmount,
    fetchUploadInsurance,
    fetchAddBeneficiaryToSubscription,
    fetchGetSubscriptionList,
    fetchDeleteBeneficiary
})(
    DeleteBeneficiaryScreen,
);
