/**
 * Project iLinkWorld
 * File DemandeAutorisationSoinScreen
 * Path screens/wallet/user
 * Created by BRICE ZELE
 * Date: 01/02/2022
 */
import React, {useEffect, useRef, useState} from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    FlatList,
    KeyboardAvoidingView,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    View,
} from 'react-native';
import {connect, useDispatch} from 'react-redux';
import {Color} from "../../../config/Color";
import I18n from 'react-native-i18n';
import {ScreenComponent} from "../../../components/ScreenComponent";
import {
    fetchAcceptRejectConsultation,
    fetchAcceptRejectConsultationReset,
    fetchActivePaySubscription,
    fetchDemaneAutorisationSoin,
    fetchDemaneAutorisationSoinReset,
    fetchGetConsultationReset,
    fetchGetListInsuranceReset,
    fetchGetListInsuranceWithBeneficiaries,
    fetchGetNetworkActs,
    fetchGetUserByIdQRCode,
    fetchGetUserByIdQRCodeReset,
    fetchGetUserByNameOrNumber,
    fetchGetUserByNameOrNumberReset
} from "../../../redux/insurance/insurance.actions";
import DropdownAlert from "react-native-dropdownalert";
import {createStructuredSelector} from "reselect";
import {
    selectActivatePaySubscription,
    selectDemandeAutorisationSoin,
    selectGetConsultation,
    selectGetNetworkAct,
    selectGetUserByIdQRCode,
    selectGetUserByNameOrNumber,
    selectInsuranceList,
    selectSubscriptionList
} from "../../../redux/insurance/insurance.selector";
import Text from '../../../components/Text';
import * as Utils from "../../../utils/UtilsFunction";
import Dialog from "react-native-dialog";
import {store} from "../../../redux/store";
import {useFormik} from "formik";
import * as Animatable from "react-native-animatable";
import {responsiveWidth} from "react-native-responsive-dimensions";
import {Dropdown} from "react-native-material-dropdown-v2";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import Button from "../../../components/Button";
import * as Yup from "yup";
import SpinnerOverlay from "../../../components/SpinnerOverlayComponent";
import Modal from "react-native-modal";
import QRCodeScanner from "react-native-qrcode-scanner";
import {RNCamera} from "react-native-camera";
import TextInput from "../../../components/TextInput";
import Icon from "react-native-vector-icons/FontAwesome5";
import SwitchSelector from "react-native-switch-selector";
import StepHeader from "../../../components/StepHeaderComponent";
import Wizard from "react-native-wizard";
import {readUser} from "../../../webservice/AuthApi";


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

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

const DemandeAutorisationSoinScreen = ({
                                           navigation,
                                           fetchGetNetworkActs,
                                           fetchAcceptRejectConsultation,
                                           fetchGetListInsuranceWithBeneficiaries,
                                           fetchDemaneAutorisationSoin,
                                           fetchGetUserByIdQRCode,
                                           fetchGetUserByNameOrNumber,
                                           getConsultation,
                                           getUserByNameOrNumber,
                                           getUserByIdQRCode,
                                           insuranceList,
                                           getNetworkAct,
                                           subscriptionList,
                                           demandeAutorisationSoin
                                       }) => {
    const dispatch = useDispatch();
    const [user, setUser] = useState(null);
    const [displayModalHistory, setDisplayModalHistory] = useState(false);
    const [historyItemDetail, setHistoryItemDetail] = useState({});
    const [wallet] = useState(store.getState().walletDetailReducer.result.response);
    const [insurances, setInsurances] = useState([]);
    const [beneficiaries, setBeneficiaries] = useState([]);
    const [beneficiaryId, setBeneficiaryId] = useState(null);
    const [insurance, setInsurance] = useState(null);

    const [showQRCodeScanner, setShowQRCodeScanner] = useState(false);
    const [showDateAccidentPicker, setShowDateAccidentPicker] = useState(false);

    const [isNumeroAssureSearch, setIsNumeroAssureSearch] = useState(false);
    const [isPhoneAssureSearch, setIsPhoneAssureSearch] = useState(false);

    const [assure, setAssure] = useState(null);
    const [beneficiary, setBeneficiary] = useState(null);
    const [medicament, setMedicament] = useState(null);
    const wizard = useRef();
    const [isFirstStep, setIsFirstStep] = useState(true);
    const [isLastStep, setIsLastStep] = useState(false);
    const [currentStep, setCurrentStep] = useState(1);

    const [statutPatientOption] = useState([
        {label: I18n.t('AYANT_DROITS'), value: "M"},
        {label: I18n.t('ASSURE'), value: "F"},
    ]);
    const [statutPatient, setStatutPatient] = useState(1);
    const [accident] = useState([
        {label: I18n.t('YES'), value: "YES"},
        {label: I18n.t('NO'), value: "NO"},
    ]);


    let insurancesRef = null;
    let codeActeRef = null;
    const [modalListAssure, setModalListAssure] = useState(false);

    let dropDownAlertRef: any = null;

    const RegisterSchema = Yup.object().shape({
        password: Yup.string()
    });

    useEffect(() => {
        dispatch(fetchGetConsultationReset());
        dispatch(fetchGetListInsuranceReset());
        dispatch(fetchAcceptRejectConsultationReset());
        dispatch(fetchGetUserByNameOrNumberReset());
        dispatch(fetchGetUserByIdQRCodeReset());
        readUser().then((user) => {
            setUser(user);
        });
        //fetchGetNetworkActs(wallet.idNetwork, '', '&authorization_type=PRIOR');
    }, []);

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

    useEffect(() => {
        if (insuranceList.result !== null) {
            let insuranceListTemp = [];
            let beneficiariesListTemp = [];
            insuranceList.result.response.map((insuranceItem, index) => {
                insuranceListTemp.push(insuranceItem.network);
            });
            setInsurances(insuranceListTemp);
            console.log("beneficiariesListTemp", beneficiariesListTemp);
        }

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

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

                ],
                {cancelable: false}
            );
        }

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

    useEffect(() => {
        console.log("getUserByNameOrNumber.result", getUserByNameOrNumber);
        if (getUserByNameOrNumber.result !== null) {
            if (getUserByNameOrNumber.result.response.length > 0) {
                setModalListAssure(true);
                //wizard.current.next();
            } else {
                dropDownAlertRef.alertWithType(
                    'warn',
                    I18n.t('EMPTY_LIST'),
                    I18n.t('NO_ASSURE_MATCH_SEARCH'),
                );
                dispatch(fetchGetUserByNameOrNumberReset());
            }

        }

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

    const renderLoader = () => (
        <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            {Platform.OS === 'android'
                ?
                (
                    <>
                        <ProgressBarAndroid/>
                        <Text>{I18n.t('LOADING_DOTS')}</Text>

                    </>
                ) :
                <>
                    <ActivityIndicator size="large" color={'#ccc'}/>
                    <Text>{I18n.t('LOADING_DOTS')}</Text>
                </>
            }
        </View>
    );


    const renderListAssure = () => (
        <ScrollView style={{flex: 1}}>
            <View style={[styles.containModal, {backgroundColor: Color.containerBackgroundColor}]}>
                <Modal
                    isVisible={modalListAssure}
                    onSwipeComplete={() => {
                        setModalListAssure(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('LIST_ASSURE')}</Text>

                        <FlatList data={getUserByNameOrNumber.result?.response}
                                  extraData={getUserByNameOrNumber.result?.response}
                                  keyExtractor={(item, index) => index}
                                  ListEmptyComponent={<Text body2>{I18n.t('NO_ASSURE_MATCH_SEARCH')}</Text>}
                                  renderItem={({item, index}) => {
                                      return (
                                          <View style={{
                                              paddingVertical: 15,
                                              alignItems: 'flex-start',
                                          }}>
                                              <TouchableOpacity
                                                  style={[
                                                      styles.contentActionModalBottom,
                                                      {
                                                          borderBottomColor: Color.borderColor,
                                                          width: "100%",
                                                          flexDirection: 'column',
                                                      },
                                                  ]}
                                                  key={item.id}
                                                  onPress={() => {


                                                      if (item.state === 'SUSPENDED') {
                                                          Alert.alert(I18n.t('ERROR_LABEL'), I18n.t('ASSURE_SUSPENDU'),
                                                              [{
                                                                  text: I18n.t('OK'), onPress: () => {
                                                                  }
                                                              }]);
                                                      } else if (item.state !== 'PAID') {
                                                          Alert.alert(I18n.t('ERROR_LABEL'), I18n.t('ASSURE_NON_EN_REGLE'),
                                                              [{
                                                                  text: I18n.t('OK'), onPress: () => {
                                                                  }
                                                              }]);
                                                      } else {
                                                          setAssure(item);
                                                          setBeneficiary(null);
                                                          setStatutPatient(1);
                                                          setModalListAssure(false);
                                                          setFieldValue(
                                                              'lastname_patient',
                                                              item.user.lastname,
                                                          );
                                                          setFieldValue(
                                                              'firstname_patient',
                                                              item.user.firstname,
                                                          );
                                                          fetchGetNetworkActs(wallet.id_network, '', `&user_id=${item.user.id}`);
                                                          dispatch(fetchGetUserByNameOrNumberReset());
                                                          wizard.current.next();
                                                          fetchGetListInsuranceWithBeneficiaries(`?user_id=${item.user.id}`);
                                                      }
                                                  }}>
                                                  <Text body2 semibold>
                                                      {`${item.user.firstname !== null ? item.user.firstname : ''} ${item.user.lastname !== null ? item.user.lastname : ''}`}
                                                  </Text>
                                                  <Text footnote>
                                                      {`${I18n.t('MONTANT_ASSURANCE_CONSOMME')}: ${item.insurance_consumed_amount}`}
                                                  </Text>
                                                  <Text footnote>
                                                      {`${I18n.t('MONTANT_ASSURANCE_RESTANTE')}: ${item.insurance_remaining_amount}`}
                                                  </Text>
                                              </TouchableOpacity>
                                              {item.beneficiaries.map((beneficiary) => (
                                                  <TouchableOpacity style={styles.beneficiarySubSection}
                                                                    onPress={() => {
                                                                        if (item.state === 'SUSPENDED') {
                                                                            Alert.alert(I18n.t('ERROR_LABEL'), I18n.t('ASSURE_PRINCIPAL_SUSPENDU'),
                                                                                [{
                                                                                    text: I18n.t('OK'), onPress: () => {
                                                                                    }
                                                                                }]);
                                                                        } else {
                                                                            setAssure(item);
                                                                            setBeneficiary(beneficiary);
                                                                            setStatutPatient(0);
                                                                            setModalListAssure(false);
                                                                            setFieldValue(
                                                                                'lastname_patient',
                                                                                beneficiary.lastname,
                                                                            );
                                                                            setFieldValue(
                                                                                'firstname_patient',
                                                                                beneficiary.firstname,
                                                                            );
                                                                            fetchGetNetworkActs(wallet.id_network, '', `&user_id=${item.user.id}&beneficiary_id=${beneficiary.id}`);
                                                                            dispatch(fetchGetUserByNameOrNumberReset());
                                                                            wizard.current.next();
                                                                            fetchGetListInsuranceWithBeneficiaries(`?user_id=${item.user.id}&beneficiary_id=${beneficiary.id}`);
                                                                        }
                                                                    }}>
                                                      <View style={{width: 10}}/>
                                                      <View style={{paddingHorizontal: 10, alignItems: 'flex-start'}}>
                                                          <Text subhead semibold textAlign="left">
                                                              {`${beneficiary.firstname !== null ? beneficiary.firstname : ''} ${beneficiary.lastname !== null ? beneficiary.lastname : ''} (${I18n.t('AYANT_DROITS')})`}
                                                          </Text>
                                                          <Text footnote>
                                                              {`${I18n.t('MONTANT_ASSURANCE_CONSOMME')}: ${beneficiary.insurance_consumed_amount}`}
                                                          </Text>
                                                          <Text footnote>
                                                              {`${I18n.t('MONTANT_ASSURANCE_RESTANTE')}: ${beneficiary.insurance_remaining_amount}`}
                                                          </Text>
                                                      </View>
                                                  </TouchableOpacity>
                                              ))}
                                          </View>
                                      )
                                  }}/>

                        <Button
                            full
                            style={{marginTop: 10, marginBottom: 20}}
                            onPress={() => setModalListAssure(false)}>
                            {I18n.t('OK')}
                        </Button>

                    </View>
                </Modal>
            </View>
        </ScrollView>
    )

    const renderDialogQRCodeScanner = () => {

        return (
            <Dialog.Container contentStyle={{width: responsiveWidth(80)}} useNativeDriver={true}
                              visible={showQRCodeScanner}>

                <Dialog.Title>{I18n.t('SCAN')}</Dialog.Title>

                <ScrollView style={[styles.blockView, {borderBottomColor: Color.borderColor, maxHeight: 300}]}>
                    <Text>
                        {I18n.t('BRING_YOUR_CAMERA_CLOSER_TO_SCAN_QR_CODE')}
                    </Text>
                    <QRCodeScanner
                        onRead={(result) => {
                            setShowQRCodeScanner(false);
                            fetchGetUserByIdQRCode(result.data);
                        }}
                        flashMode={RNCamera.Constants.FlashMode.off}
                    />
                </ScrollView>

                <Dialog.Button bold={true} label={I18n.t('CLOSE')} onPress={() => {
                    setShowQRCodeScanner(false);
                }}/>
            </Dialog.Container>
        )
    }

    const {
        handleChange,
        handleSubmit,
        handleBlur,
        values,
        errors,
        touched,
        setFieldValue,
        setFieldTouched,
        isValid,
    } = useFormik({
        validationSchema: RegisterSchema,
        initialValues: {
            password: '',
            code_acte: '',
            firstname_patient: '',
            lastname_patient: '',
        },
        onSubmit: values => {

            if (assure !== null || beneficiary !== null) {
                if (insurance === null) {
                    insurancesRef.shake(800);
                } else if (values.code_acte === '')
                    codeActeRef.shake(200)
                else {
                    fetchDemaneAutorisationSoin({
                        act_id: values.code_acte,
                        /*insurance_id: insurance.id,*/
                        insurance_id: assure.id,
                        issuer_network_agent_id: wallet.network_agent_id,
                        beneficiary_id: beneficiary !== null ? beneficiary.id : null,
                        password: values.password
                    });
                    console.log(user);
                    console.log("insurance", insurance);
                }
            }
        },
    });


    const onNext = () => {
        console.log("currentStep", currentStep);
        switch (currentStep) {
            case 0:
                console.log("values", values);
                dispatch(fetchGetUserByNameOrNumberReset());
                if (values.numero_assure !== '' && getUserByNameOrNumber.result === null) {
                    if (isNumeroAssureSearch)
                        fetchGetUserByNameOrNumber(wallet.id_network, `&insured_id=${values.numero_assure}`);
                    else if (isPhoneAssureSearch)
                        fetchGetUserByNameOrNumber(wallet.id_network, `&phone=${values.numero_assure}`);
                    else
                        fetchGetUserByNameOrNumber(wallet.id_network, `&name=${values.numero_assure}`)
                    console.log("errors", errors);
                }
                return false;
                break;

            default:
                return true;
        }
    };

    const stepList = [
        {
            title: I18n.t('ASSURE'),
            content: (
                <View>
                    <TextInput
                        style={{marginTop: 10, width: responsiveWidth(90)}}
                        placeholder={isNumeroAssureSearch ? I18n.t('NUMERO_ASSURE') : isPhoneAssureSearch ? I18n.t('PHONE_NUMBER') : I18n.t('NOM_ASSURE')}
                        value={values.numero_assure}
                        keyboardType={isPhoneAssureSearch ? 'numeric' : 'default'}
                        onChangeText={handleChange('numero_assure')}
                        onBlur={handleBlur('numero_assure')}
                        success={touched.numero_assure && !errors.numero_assure}
                        touched={touched.numero_assure}
                        error={errors.numero_assure}
                        icon={
                            <FontAwesome
                                style={{zIndex: 10}}
                                name={isNumeroAssureSearch ? 'lock' : isPhoneAssureSearch ? 'phone' : 'user'}
                                size={20}
                            />
                        }
                    />
                    <View style={{
                        flexDirection: 'row',
                        position: 'absolute',
                        top: 22,
                        right: 70,
                        justifyContent: 'space-between',
                        width: 50
                    }}>
                        <Icon
                            style={{paddingRight: 10}}
                            name='lock'
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                setIsNumeroAssureSearch(true);
                                setIsPhoneAssureSearch(false);
                            }}
                        />
                        <Icon
                            style={{paddingRight: 10}}
                            name='phone'
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                setIsNumeroAssureSearch(false);
                                setIsPhoneAssureSearch(true);
                            }}
                        />
                        <Icon
                            style={{paddingRight: 10}}
                            name='user'
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                setIsNumeroAssureSearch(false);
                                setIsPhoneAssureSearch(false);
                            }}
                        />
                        <Icon
                            style={{paddingRight: 10}}
                            name="qrcode"
                            size={20}
                            color={Color.primaryColor}
                            onPress={() => {
                                setShowQRCodeScanner(true);
                            }}
                        />
                    </View>
                </View>
            ),
        },
        {
            title: I18n.t('PATIENT'),
            content: (
                <View>
                    <TextInput
                        style={{marginTop: 10}}
                        placeholder={I18n.t('NOM_CLIENT')}
                        value={values.lastname_patient}
                        onChangeText={handleChange('lastname_patient')}
                        onBlur={handleBlur('lastname_patient')}
                        success={touched.lastname_patient && !errors.lastname_patient}
                        touched={touched.lastname_patient}
                        editable={false}
                        error={errors.lastname_patient}
                    />

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

                    <View style={{
                        marginTop: 10,
                        flexDirection: 'row',
                        justifyContent: "space-between"
                    }}>
                        <Text body2>{I18n.t('SITUATION')}</Text>
                        <View style={{width: responsiveWidth(60)}}>
                            <SwitchSelector options={statutPatientOption}
                                            disabled={true}
                                            value={statutPatient}
                                            initial={statutPatient}
                                            buttonColor={Color.accentColor}
                                            backgroundColor={Color.primaryDarkColor}
                                            textColor='white'
                                            bold={true}
                                            hasPadding
                                            height={32}
                                            onPress={(value) => {
                                                //setGender(value);
                                            }}/>
                        </View>
                    </View>
                </View>
            ),
        },
        {
            title: I18n.t('DEMAND_DETAIL'),
            content: (
                <View>
                    {
                        insuranceList.loading
                            ? renderLoader()
                            : insuranceList.result ?
                                <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={insuranceList.result.response}
                                            useNativeDriver={true}
                                            onChangeText={(value, index, data) => {
                                                console.log("Value", value);
                                                setInsurance(value);
                                                setBeneficiaries([...value.beneficiaries, {
                                                    id: assure !== null ? assure.id : beneficiary.id,
                                                    firstname: assure !== null ? assure.firstname : beneficiary.firstname,
                                                    lastname: assure !== null ? assure.lastname : beneficiary.lastname
                                                }]);
                                                fetchGetNetworkActs(value.network.id, '', '&authorization_type=PRIOR')
                                            }}
                                            valueExtractor={(value) => {
                                                return value
                                            }}
                                            labelExtractor={(value) => {
                                                return value.network.name
                                            }}
                                        />
                                    </Animatable.View>

                                    <Animatable.View ref={(comp) => {
                                        codeActeRef = comp
                                    }}
                                                     style={{
                                                         width: responsiveWidth(90),
                                                         height: 60,
                                                         alignSelf: 'center',
                                                         borderRadius: 10,
                                                         paddingLeft: 20,
                                                         marginTop: 10,
                                                         paddingRight: 20,
                                                         backgroundColor: 'white'
                                                     }}>
                                        <Dropdown
                                            label={I18n.t('CODE_ACTE')}
                                            data={getNetworkAct.result !== null ? getNetworkAct.result?.response : []}
                                            useNativeDriver={true}
                                            onChangeText={(value, index, data) => {
                                                setFieldTouched('code_acte');
                                                setFieldValue('code_acte', value.id);
                                            }}
                                            valueExtractor={(value) => {
                                                return value
                                            }}
                                            labelExtractor={(value) => {
                                                return value.name
                                            }}
                                        />
                                    </Animatable.View>

                                    {
                                        wallet.password_validation === "MAX" &&
                                        <TextInput
                                            style={{marginTop: 10, width: responsiveWidth(90)}}
                                            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={demandeAutorisationSoin.loading}
                                        onPress={handleSubmit}>
                                        {I18n.t('SUBMIT_LABEL')}
                                    </Button>
                                </View>
                                : null}
                </View>
            ),
        }
    ]

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

                <ScrollView style={{flex: 1}}>

                    <View style={styles.contain}>

                        <StepHeader
                            steps={stepList}
                            currentStepIndex={currentStep + 1}
                        />

                        <View
                            style={{
                                flexDirection: 'column',
                                alignItems: 'center',
                            }}>
                            <Wizard
                                ref={wizard}
                                activeStep={0}
                                steps={stepList}
                                useNativeDriver
                                nextStepAnimation="slideLeft"
                                prevStepAnimation="slideRight"
                                isFirstStep={val =>
                                    setIsFirstStep(val)
                                }
                                isLastStep={val =>
                                    setIsLastStep(val)
                                }
                                onNext={() => {
                                    onNext();
                                }}
                                onPrev={() => {
                                }}
                                currentStep={({
                                                  currentStep,
                                                  isLastStep,
                                                  isFirstStep,
                                              }) => {
                                    setCurrentStep(currentStep);
                                    setIsFirstStep(isFirstStep);
                                    setIsLastStep(isLastStep);
                                }}
                            />
                        </View>

                        <View style={styles.iconNavigation}>
                            {!isFirstStep ? (
                                <TouchableOpacity
                                    style={[
                                        styles.iconNavigationButton,
                                        {
                                            backgroundColor:
                                            Color.primaryColor,
                                            borderColor:
                                            Color.primaryColor,
                                        },
                                    ]}
                                    onPress={() =>
                                        wizard.current.prev()
                                    }>
                                    <Icon
                                        name="arrow-left"
                                        size={20}
                                        color={Color.whiteColor}
                                    />
                                </TouchableOpacity>
                            ) : (
                                <View/>
                            )}
                            {currentStep === 2 ? (
                                <Button
                                    loading={demandeAutorisationSoin.loading}
                                    onPress={handleSubmit}>
                                    {I18n.t('SUBMIT_LABEL')}
                                </Button>
                            ) : (
                                <TouchableOpacity
                                    style={[
                                        styles.iconNavigationButton,
                                        {
                                            backgroundColor:
                                            Color.primaryColor,
                                            borderColor:
                                            Color.primaryColor,
                                        },
                                    ]}
                                    onPress={e => {
                                        handleSubmit(e);
                                        if (onNext())
                                            wizard.current.next();
                                    }}>
                                    {(subscriptionList.loading || getUserByNameOrNumber.loading || getUserByIdQRCode.loading) ?
                                        <ActivityIndicator
                                            size="small"
                                            color="#fff"
                                        />
                                        : <Icon
                                            name="arrow-right"
                                            size={24}
                                            color={Color.whiteColor}
                                        />}
                                </TouchableOpacity>
                            )}
                        </View>
                        {modalListAssure && renderListAssure()}
                        {showQRCodeScanner && renderDialogQRCodeScanner()}
                        {modalListAssure && renderListAssure()}
                    </View>
                </ScrollView>
            </KeyboardAvoidingView>

            {/*                {getConsultation.loading
                    ? renderLoader()
                    : getConsultation.result !== null ?
                        (
                            <FlatList
                                style={{flex: 1}}
                                ListEmptyComponent={() => {
                                    return (
                                        <Text>{I18n.t('NO_CONSULTATION_DEMAND')}</Text>
                                    )
                                }}
                                data={[]}
                                keyExtractor={(item, index) => item.id}
                                renderItem={({item, index}) => (
                                    renderItem(item)
                                )}
                            />
                        )
                        : null}*/}
        </ScreenComponent>
    )
};

const mapStateToProps = createStructuredSelector({
    subscriptionList: selectSubscriptionList,
    insuranceList: selectInsuranceList,
    activatePaySubscription: selectActivatePaySubscription,
    getConsultation: selectGetConsultation,
    getNetworkAct: selectGetNetworkAct,
    demandeAutorisationSoin: selectDemandeAutorisationSoin,
    getUserByNameOrNumber: selectGetUserByNameOrNumber,
    getUserByIdQRCode: selectGetUserByIdQRCode,
});

export default connect(mapStateToProps, {
    fetchActivePaySubscription,
    fetchGetNetworkActs,
    fetchAcceptRejectConsultation,
    fetchGetListInsuranceWithBeneficiaries,
    fetchDemaneAutorisationSoin,
    fetchGetUserByIdQRCode,
    fetchGetUserByNameOrNumber,
})(
    DemandeAutorisationSoinScreen,
);
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: {
        marginTop: 20,
        paddingBottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        flex: 1,
    },
    content: {
        padding: 10,
        marginBottom: 10,
        borderRadius: 8
    },
    contentTop: {
        flexDirection: "row",
        paddingBottom: 10,
        borderBottomWidth: 1
    },

    contentBottom: {
        flexDirection: "row",
        marginTop: 10,
        justifyContent: "space-between"
    },
    bottomLeft: {flexDirection: "row", alignItems: "center"},
    image: {width: 32, height: 32, marginRight: 10, borderRadius: 16},
    blockView: {
        paddingVertical: 10,
        borderBottomWidth: 0.5,
    },
    ineSeparator: {
        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: 10,
        marginBottom: 10,
        justifyContent: "space-between",
        borderBottomWidth: 1
    },
    containModal: {
        paddingVertical: 10,
        paddingHorizontal: 20,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    iconNavigation: {
        width: '100%',
        flexDirection: 'row',
        marginTop: 20,
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    iconNavigationButton: {
        borderWidth: 1,
        borderRadius: 25,
        width: 50,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center'
    },
    beneficiarySubSection: {
        marginTop: 10,
        flexDirection: 'row',
        width: '100%',
    }
});
