/**
 * Project iLinkWorld
 * File InsuranceSubscriptionScreen
 * Path screens/wallet/user
 * Created by BRICE ZELE
 * Date: 18/10/2021
 */
import React, {useEffect, useState} from 'react';
import {
    Alert,
    Dimensions,
    FlatList,
    Image,
    Keyboard,
    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 {Color} from "../../../config/Color";
import I18n from 'react-native-i18n';
import {ScreenComponent} from "../../../components/ScreenComponent";
import TextInput from '../../../components/TextInput';
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 SwitchSelector from "react-native-switch-selector";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import {
    fetchAddBeneficiaryToSubscription,
    fetchAddBeneficiaryToSubscriptionReset,
    fetchGetInsurancePrimeAmount,
    fetchGetListInsurance,
    fetchGetListInsuranceReset,
    fetchGetSubscriptionList,
    fetchGetSubscriptionListReset,
    fetchSubscribeInsurance,
    fetchSubscribeInsuranceReset,
    fetchUploadInsurance,
    fetchUploadInsuranceReset
} from "../../../redux/insurance/insurance.actions";
import DropdownAlert from "react-native-dropdownalert";
import {readUser} from "../../../webservice/AuthApi";
import ImagePicker from "react-native-image-crop-picker";
import DateTimePicker from "@react-native-community/datetimepicker";
import * as Animatable from 'react-native-animatable';
import {createStructuredSelector} from "reselect";
import {
    selectAddBeneficiaryToSubscription,
    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 AddBeneficiaryScreen = ({
                                  insuranceList,
                                  subscribeInsurance,
                                  insurancePrimeAmount,
                                  fetchSubscribeInsurance,
                                  fetchGetListInsurance,
                                  fetchGetInsurancePrimeAmount,
                                  fetchUploadInsurance,
                                  uploadInsuranceImages,
                                  fetchAddBeneficiaryToSubscription,
                                  addBeneficiaryToSubscription,
                                  fetchGetSubscriptionList,
                                  subscriptionList,
                                  navigation
                              }) => {

    const [modalVisible, setModalVisible] = useState(false);
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [user, setUser] = useState(null);
    const [insurance, setInsurance] = useState(null);
    const [amountPerMonth, setAmountPerMonth] = useState(null);

    useEffect(() => {
        console.log("amountPerMonth", amountPerMonth);
    });
    const [firstNameBeneficiary, setFirstNameBeneficiary] = useState(null);
    const [lastNameBeneficiary, setLastNameBeneficiary] = useState(null);
    const [password, setPassword] = useState(null);
    let fileToSendTemp = new FormData();
    let [fileToSend, setFileToSend] = useState(null);
    let [fileAdded, setFileAdded] = useState([]);
    const dispatch = useDispatch();
    let dropDownAlertRef: any = null;
    const [insurances, setInsurances] = useState([]);
    const [validationOption, setValidationOption] = useState([
        {label: I18n.t('YES'), value: 0},
        {label: I18n.t('NO'), value: 1},
    ]);
    const [sexeOption] = useState([
        {label: I18n.t('MASCULIN'), value: "M"},
        {label: I18n.t('FEMININ'), value: "F"},
    ]);
    const [dateNaissance, setDateNaissance] = useState('' + moment(new Date(((new Date()).getFullYear() - 5), 0, 1)).format('YYYY-MM-DD'));
    const [showDateNaissancePicker, setShowDateNaissancePicker] = useState(false);
    const [showModalDetail, setShowModalDetail] = useState(false);
    const [modalViewBeneficiariesVisible, setModalViewBeneficiariesVisible] = useState(false);
    const [gender, setGender] = useState('M');
    const [affiliations] = useState([
        {label: I18n.t('ENFANT'), value: "CHILD"},
        {label: I18n.t('CONJOINT'), value: 'SPOUSE'},
    ]);
    const [affiliation, setAffliliation] = useState('CHILD');
    const [subscription, setSubscription] = useState(null);
    const [subscriptions, setSubscriptions] = useState([]);
    const [wallet] = useState(store.getState().walletDetailReducer.result.response);

    let [currentYearMinusAgeLimit, setCurrentYearMinusAgeLimit] = useState(new Date(((new Date()).getFullYear() - 5), 0, 1));
    let subscriptionRef = null;

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

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

    useEffect(() => {
        console.log('Beneficiaries', beneficiaries);
    }, [beneficiaries]);

    useEffect(() => {
        if (subscription !== null)
            console.log('Subscription', subscription);
    }, [subscription]);

    useEffect(() => {
        console.log("currentYearMinusAgeLimit", currentYearMinusAgeLimit);
    }, currentYearMinusAgeLimit);

    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 (addBeneficiaryToSubscription.result !== null) {
            Alert.alert(
                I18n.t("SUCCESS"),
                addBeneficiaryToSubscription.result.response,
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchAddBeneficiaryToSubscriptionReset());
                            navigation.goBack();
                        }
                    }

                ],
                {cancelable: false}
            )
        }

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


    useEffect(() => {
        if (uploadInsuranceImages.result !== null) {
            setModalVisible(false);

            if (subscription !== null) {
                if (beneficiaries.length === parseInt(subscription.max_number_of_beneficiaries)) {
                    Alert.alert(
                        I18n.t("ERROR_LABLE"),
                        I18n.t('NUMBER_MAX_BENEFICIARY'),
                        [
                            {
                                text: I18n.t("OK"), onPress: () => {
                                }
                            }
                        ],
                        { cancelable: false }
                    );
/*                    dropDownAlertRef.alertWithType(
                        'error',
                        I18n.t('ERROR_LABEL'),
                        I18n.t('NUMBER_MAX_BENEFICIARY'),
                    );*/
                } else {
                    console.log("affiliation", affiliation);
                    let beneficiariesTemp = beneficiaries;
                    setBeneficiaries([{
                        lastname: lastNameBeneficiary,
                        firstname: firstNameBeneficiary,
                        gender: gender,
                        birthdate: moment(dateNaissance).format('YYYY-MM-DD'),
                        affiliation: affiliation,
                        birthdate_proof: childAyantDroitDocument[1].checboxSelectedValue,
                        profile_image: uploadInsuranceImages.result.response[0],
                        birthdate_proof_doc: uploadInsuranceImages.result.response[1],
                        justice_doc: uploadInsuranceImages.result.response.length > 1 ? uploadInsuranceImages.result.response[2] : null,
                        marriage_certificate_doc: uploadInsuranceImages.result.response[1],
                        id_document_type: "CNI",
                        id_document_front: uploadInsuranceImages.result.response[2],
                        id_document_back: uploadInsuranceImages.result.response[3],
                        isEditable: true
                    }, ...beneficiaries]);
                    dropDownAlertRef.alertWithType(
                        'success',
                        I18n.t('SUCCESS'),
                        I18n.t('BENEFICIARY_SUCCESSFULLY_ADDED'),
                    );
                    setModalVisible(false);
                }
            }
        }

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

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

    const AddBeneficiarySchema = Yup.object().shape({
        lastname: Yup.string().required(I18n.t('THIS_FIELD_IS_REQUIRED')),
        firstname: Yup.string(),
    });


    const createFormData = (key, photo) => {
        if (fileToSend !== null)
            fileToSendTemp = fileToSend;

        fileToSendTemp.append("files[]", {
            name: photo.path.split('/').pop(),
            type: photo.mime,
            uri:
                Platform.OS === "android" ? photo.path : photo.path.replace("file://", "")
        });
        setFileAdded([key, ...fileAdded]);
        setFileToSend(fileToSendTemp);

    }

    const [childAyantDroitDocument, setChildAyantDroitDocument] = useState([
        {
            label: I18n.t('PROFILE_PICTURE'),
            name: 'profile_image',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        },
        {
            label: I18n.t('COPIE_LEGALISE_ACTE_NAISSANCE_CERTIFICAT_NAISSANCE'),
            name: 'birthdate_proof_doc',
            isFrontCamera: false,
            file: null,
            hasCheckbox: true,
            checkboxValue: ['CERTIFICATE', 'CERTIFIED_COPY'],
            checboxSelectedValue: 'CERTIFICATE',
        },
        {
            label: I18n.t('DOCUMENT_JUSTICE_ENFANT_ADOPTE'),
            name: 'justice_doc',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        }
    ]);
    const [beneficiaries, setBeneficiaries] = useState([]);

    const [conjointAyantDroitDocument, setConjointAyantDroitDocument] = useState([
        {
            label: I18n.t('PROFILE_PICTURE'),
            name: 'profile_image',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        },
        {
            label: I18n.t('ACTE_MARIAGE'),
            name: 'marriage_certificate_doc',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        },
        {
            label: I18n.t('CNI_FRONT_FACE'),
            name: 'id_document_front',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        },
        {
            label: I18n.t('CNI_BACK_FACE'),
            name: 'id_document_back',
            isFrontCamera: false,
            file: null,
            hasCheckbox: false,
        }
    ]);

    const handleTakePhotoFromCamera = (name, isFrontCamera = false) => {
        ImagePicker.openCamera({
            cropping: true,
            compressImageQuality: 0.7,
            useFrontCamera: false
        }).then(image => {
            if (affiliation === "CHILD") {
                let tempChildAyantDroitDocument = childAyantDroitDocument;
                setChildAyantDroitDocument(tempChildAyantDroitDocument.map(childAyantDroit => {
                    if (name === childAyantDroit.name) {
                        if (childAyantDroit.hasCheckbox) {
                            return {
                                label: childAyantDroit.label,
                                name: childAyantDroit.name,
                                isFrontCamera: childAyantDroit.isFrontCamera,
                                file: image,
                                hasCheckbox: childAyantDroit.hasCheckbox,
                                checkboxValue: childAyantDroit.checkboxValue,
                                checboxSelectedValue: childAyantDroit.checboxSelectedValue,
                            };
                        } else {
                            return {
                                label: childAyantDroit.label,
                                name: childAyantDroit.name,
                                isFrontCamera: childAyantDroit.isFrontCamera,
                                file: image
                            }
                        }
                    } else
                        return childAyantDroit;
                }));
            } else {
                setConjointAyantDroitDocument(conjointAyantDroitDocument.map(conjointAyantDroit => {
                    if (name === conjointAyantDroit.name) {
                        if (conjointAyantDroit.hasCheckbox) {
                            return {
                                label: conjointAyantDroit.label,
                                name: conjointAyantDroit.name,
                                isFrontCamera: conjointAyantDroit.isFrontCamera,
                                file: image,
                                hasCheckbox: conjointAyantDroit.hasCheckbox,
                                checkboxValue: conjointAyantDroit.checkboxValue,
                                checboxSelectedValue: conjointAyantDroit.checboxSelectedValue,
                            };
                        } else {
                            return {
                                label: conjointAyantDroit.label,
                                name: conjointAyantDroit.name,
                                isFrontCamera: conjointAyantDroit.isFrontCamera,
                                file: image
                            }
                        }
                    } else
                        return conjointAyantDroit;
                }));
            }
            createFormData(name, image);
        });
    };

    const onChangeDateNaissance = (event, selectedDate) => {
        const currentDate = selectedDate || dateNaissance;
        setShowDateNaissancePicker(Platform.OS === 'ios');
        setDateNaissance(currentDate);
    };

    const renderDateNaissancePicker = () => {
        return (<DateTimePicker
                timeZoneOffsetInMinutes={0}
                is24Hour={true}
                value={new Date(dateNaissance)}
                mode='date'
                minimumDate={currentYearMinusAgeLimit}
                display="spinner"
                onChange={onChangeDateNaissance}
            />
        );
    }

    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.concat(subscription.beneficiaries)}
                            extraData={beneficiaries.concat(subscription.beneficiaries)}
                            keyExtractor={(item, index) => index}
                            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}>
                                            {item.hasOwnProperty('isEditable') &&
                                            <TouchableOpacity
                                                onPress={() => {
                                                    let beneficiariesTemp = beneficiaries;
                                                    console.log("beneficiariesTemp index", index);
                                                    beneficiariesTemp.splice(index);
                                                    console.log("beneficiariesTemp", beneficiariesTemp);
                                                    setBeneficiaries([...beneficiariesTemp]);
                                                }}>
                                                <Icon
                                                    name="minus-circle"
                                                    size={24}
                                                    color={Color.grayColor}
                                                />
                                            </TouchableOpacity>}
                                        </View>
                                    </View>
                                );
                            }}/>
                    </View>

                    <Button
                        style={{marginTop: 20, marginBottom: 20}}
                        full
                        onPress={() => {
                            setModalViewBeneficiariesVisible(false)
                        }}>
                        {I18n.t('OK')}
                    </Button>
                </View>
            </Modal>
        );
    };


    const renderAddNewIdentification = () => (
        <Formik validationSchema={AddBeneficiarySchema}
                initialValues={{
                    firstname: '',
                    lastname: '',
                }}
                onSubmit={(values) => {
                    fetchUploadInsurance(fileToSend);
                    setFirstNameBeneficiary(values.firstname);
                    setLastNameBeneficiary(values.lastname);
                }}>

            {({
                  values,
                  errors,
                  touched,
                  handleChange,
                  handleBlur,
                  handleSubmit,
                  isSubmitting,
              }) => (
                <ScrollView style={{flex: 1}}>
                    <View style={[styles.containModal, {backgroundColor: Color.containerBackgroundColor}]}>
                        <Modal
                            isVisible={modalVisible}
                            onSwipeComplete={() => {
                                setModalVisible(false);
                            }}
                            swipeDirection={['down']}
                            style={styles.bottomModal}>
                            <View
                                style={[
                                    styles.contentFilterBottom,
                                    {backgroundColor: Color.containerBackgroundColor},
                                ]}>
                                <View style={styles.contentSwipeDown}>
                                    <View style={styles.lineSwipeDown}/>
                                </View>

                                <Text body2 style={{marginTop: 10}}>{I18n.t('ADD_AYANT_DROIT')}</Text>

                                <TextInput
                                    style={{marginTop: 10}}
                                    placeholder={I18n.t('NOM_ASSURE')}
                                    value={values.lastname}
                                    onChangeText={handleChange('lastname')}
                                    onBlur={handleBlur('lastname')}
                                    success={touched.lastname && !errors.lastname}
                                    touched={touched.lastname}
                                    error={errors.lastname}
                                />

                                <TextInput
                                    style={{marginTop: 10}}
                                    placeholder={I18n.t('PRENOM_ASSURE')}
                                    value={values.firstname}
                                    onChangeText={handleChange('firstname')}
                                    onBlur={handleBlur('firstname')}
                                    success={touched.firstname && !errors.firstname}
                                    touched={touched.firstname}
                                    error={errors.firstname}
                                />

                                <TextInput
                                    style={{marginTop: 10}}
                                    placeholder={I18n.t('DATE_NAISSANCE')}
                                    value={'' + moment(dateNaissance).format('YYYY-MM-DD')}
                                    onChangeText={handleChange('birthdate')}
                                    onBlur={handleBlur('birthdate')}
                                    onFocus={() => {
                                        Keyboard.dismiss();
                                        setShowDateNaissancePicker(true);
                                    }}
                                    success={touched.birthdate && !errors.birthdate}
                                    touched={touched.birthdate}
                                    error={errors.birthdate}
                                />

                                <View style={{
                                    marginTop: 10,
                                    width: "100%",
                                    flexDirection: 'row',
                                    justifyContent: "space-between"
                                }}>
                                    <Text body2>{I18n.t('SEXE')}</Text>
                                    <View style={styles.contentSwitch}>
                                        <SwitchSelector options={sexeOption}
                                                        initial={0}
                                                        buttonColor={Color.accentColor}
                                                        backgroundColor={Color.primaryDarkColor}
                                                        textColor='white'
                                                        bold={true}
                                                        hasPadding
                                                        height={32}
                                                        onPress={(value) => {
                                                            setGender(value);
                                                        }}/>
                                    </View>
                                </View>

                                <View style={{
                                    marginTop: 10,
                                    width: "100%",
                                    flexDirection: 'row',
                                    justifyContent: "space-between"
                                }}>
                                    <Text body2>{I18n.t('AFFILIATION')}</Text>
                                    <View style={styles.contentSwitch}>
                                        <SwitchSelector options={affiliations}
                                                        initial={0}
                                                        buttonColor={Color.accentColor}
                                                        backgroundColor={Color.primaryDarkColor}
                                                        textColor='white'
                                                        bold={true}
                                                        hasPadding
                                                        height={32}
                                                        onPress={(value) => {
                                                            setFileAdded([]);
                                                            if (value === 'CHILD')
                                                                setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription.network.age_limit_of_child_beneficiary)), 0, 1));
                                                            else
                                                                setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription.network.age_limit_of_insured_and_spouse)), 0, 1));
                                                            setAffliliation(value);
                                                        }}/>
                                    </View>
                                </View>

                                <View style={styles.contentService}>
                                    <FlatList
                                        horizontal={true}
                                        showsHorizontalScrollIndicator={false}
                                        data={affiliation === 'CHILD' ? childAyantDroitDocument : conjointAyantDroitDocument}
                                        extraData={affiliation === 'CHILD' ? childAyantDroitDocument : conjointAyantDroitDocument}
                                        keyExtractor={(item, index) => index}
                                        renderItem={({item, index}) => {
                                            if (index === 0) {
                                                return (
                                                    <TouchableOpacity style={styles.choosePhotoBtn}
                                                                      onPress={() => handleTakePhotoFromCamera(item.name, item.isFrontCamera)}>
                                                        {item.file === null
                                                            ? <MaterialCommunityIcons name="camera-image" size={50}
                                                                                      color={Color.accentColor}/>
                                                            :
                                                            <Image source={{uri: item.file.path}}
                                                                   style={{width: 50, height: 50}}/>
                                                        }
                                                        <Text style={{alignSelf: 'flex-start', fontSize: 13}}
                                                              textAlign='center'>{item.label}</Text>

                                                    </TouchableOpacity>
                                                );
                                            } else {
                                                return (
                                                    <TouchableOpacity style={styles.choosePhotoBtn}
                                                                      onPress={() => handleTakePhotoFromCamera(item.name, item.isFrontCamera)}
                                                                      disabled={!fileAdded.includes(affiliation === 'CHILD' ? childAyantDroitDocument[index - 1].name : conjointAyantDroitDocument[index - 1].name)}>
                                                        {item.file === null
                                                            ? <MaterialCommunityIcons name="camera-image" size={50}
                                                                                      color={(!fileAdded.includes(affiliation === 'CHILD' ? childAyantDroitDocument[index - 1].name : conjointAyantDroitDocument[index - 1].name)) ? Color.grayColor : Color.accentColor}/>
                                                            :
                                                            <Image source={{uri: item.file.path}}
                                                                   style={{width: 50, height: 50}}/>
                                                        }
                                                        <Text style={{alignSelf: 'flex-start', fontSize: 13}}
                                                              textAlign='center'>{item.label}</Text>
                                                    </TouchableOpacity>
                                                );
                                            }

                                        }}
                                    />
                                </View>

                                <Button
                                    style={{marginTop: 20, marginBottom: 20}}
                                    full
                                    loading={uploadInsuranceImages.loading || subscribeInsurance.loading}
                                    onPress={handleSubmit}>
                                    {I18n.t('SUBMIT_LABEL')}
                                </Button>
                            </View>
                        </Modal>
                    </View>
                </ScrollView>
            )}
        </Formik>
    );

    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);
                                        fetchAddBeneficiaryToSubscription(subscription.id, {
                                            password: values.password,
                                            beneficiaries
                                        });
                                    }
                                }
                            }}>

                        {({
                              values,
                              errors,
                              touched,
                              handleChange,
                              handleBlur,
                              handleSubmit,
                              isSubmitting,
                          }) => (
                            <View style={styles.contain}>
                                {/*                                <Animatable.View ref={(comp) => {
                                    insurancesRef = comp
                                }}
                                                 style={{
                                                     width: responsiveWidth(90),
                                                     height: 60,
                                                     alignSelf: 'center',
                                                     borderRadius: 10,
                                                     paddingLeft: 20,
                                                     paddingRight: 20,
                                                     backgroundColor: 'white'
                                                 }}>
                                    <Dropdown
                                        label={I18n.t('SELECT_INSURANCE')}
                                        data={insurances}
                                        useNativeDriver={true}
                                        onChangeText={(value, index, data) => {
                                            console.log("Value", value);
                                            setInsurance(
                                                {
                                                    age_limit_of_child_beneficiary: value.age_limit_of_child_beneficiary,
                                                    age_limit_of_insured_and_spouse: value.age_limit_of_insured_and_spouse,
                                                    id: value.id,
                                                    max_number_of_beneficiaries: value.max_number_of_beneficiaries,
                                                    name: value.name,
                                                    months_prices: value.months_prices.map((item, index) => {
                                                        return {
                                                            id: item.id,
                                                            number_of_months: item.number_of_months,
                                                            min_amount: item.min_amount,
                                                            checked: index === 0,
                                                        };
                                                    })
                                                }
                                            );
                                            setAmountPerMonth(value.months_prices[0]);
                                        }}
                                        valueExtractor={(value) => {
                                            return value
                                        }}
                                        labelExtractor={(value) => {
                                            return value.name
                                        }}
                                    />
                                </Animatable.View>*/}

                                <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);
                                            setSubscription(
                                                {
                                                    id: value.id,
                                                    network: value.network,
                                                    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,
                                                    insured_id: value.insured_id,
                                                    subscription: value.subscription,
                                                    beneficiaries: value.beneficiaries
                                                }
                                            );
                                        }}
                                        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}
                                    />
                                <View
                                    style={{
                                        flexDirection: 'column',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        marginTop: 25,
                                    }}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            if (subscription === null) {
                                                dropDownAlertRef.alertWithType(
                                                    'warn',
                                                    I18n.t('ERROR_LABEL'),
                                                    I18n.t('PLEASE_SELECT_INSURANCE_BEFORE'),
                                                );
                                            } else {
                                                console.log("Souscription", subscription);
                                                setModalVisible(true);
                                                setShowDateNaissancePicker(false);
                                                dispatch(fetchUploadInsuranceReset());
                                                setAffliliation('CHILD');
                                                setCurrentYearMinusAgeLimit(new Date(((new Date()).getFullYear() - parseInt(subscription?.network?.age_limit_of_child_beneficiary)), 0, 1));
                                                setDateNaissance('' + moment(new Date(((new Date()).getFullYear() - parseInt(subscription?.network?.age_limit_of_child_beneficiary)), 0, 1)).format('YYYY-MM-DD'));
                                                setFirstNameBeneficiary(null);
                                                setLastNameBeneficiary(null);
                                                setFileAdded([]);
                                                //setDateNaissance('' + moment().subtract(5, 'years').format());
                                            }

                                        }}>
                                        <Text body1 primaryColor bold>
                                            {I18n.t('ADD_AYANT_DROIT')}
                                        </Text>
                                    </TouchableOpacity>
                                </View>

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

                </ScrollView>
            </KeyboardAvoidingView>
            {modalVisible && renderAddNewIdentification()}
            {modalViewBeneficiariesVisible && renderModalViewBeneficiaries()}
            {showDateNaissancePicker && renderDateNaissancePicker()}
            {(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.concat(subscription.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
});

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