/**
 * Project iLinkWorld
 * File HistoricNanoSanteUserScreen
 * Path screens/wallet/user
 * Created by BRICE ZELE
 * Date: 26/01/2022
 */
import React, {useEffect, useState} from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    FlatList,
    Platform,
    ProgressBarAndroid,
    ScrollView,
    StyleSheet,
    TouchableOpacity,
    View,
} from 'react-native';
import isNil from 'lodash/isNil';
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,
    fetchGetConsultation,
    fetchGetConsultationReset,
    fetchGetDemandeAutorisationSoin,
    fetchGetInvoiceHistory,
    fetchGetSubscription
} from "../../../redux/insurance/insurance.actions";
import DropdownAlert from "react-native-dropdownalert";
import {createStructuredSelector} from "reselect";
import {
    selectAcceptRefuseConsultation,
    selectActivatePaySubscription,
    selectGetConsultation,
    selectSubscriptionList
} from "../../../redux/insurance/insurance.selector";
import {readUser} from "../../../webservice/AuthApi";
import Text from '../../../components/Text';
import * as Utils from "../../../utils/UtilsFunction";
import {uppercaseFirstLetter} from "../../../utils/UtilsFunction";
import Dialog from "react-native-dialog";
import {Typography} from "../../../config/typography";
import Tag from "../../../components/Tag";
import FontAwesome5 from "react-native-vector-icons/FontAwesome5";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import {store} from "../../../redux/store";
import AccordionComponent from "../../../components/AccordionComponent";


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

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

const HistoriqueNanoSanteAgentScreen = ({
                                           navigation,
                                           fetchGetConsultation,
                                           fetchGetSubscription,
                                            fetchGetInvoiceHistory,
                                           fetchGetDemandeAutorisationSoin,
                                           fetchAcceptRejectConsultation,
                                           acceptRefuseConsultation,
                                           getConsultation
                                       }) => {
    const dispatch = useDispatch();
    const [user, setUser] = useState(null);
    const [displayModalHistory, setDisplayModalHistory] = useState(false);
    const [historyItemDetail, setHistoryItemDetail] = useState({});
    const [page, setPage] = useState(1);
    const [historiqueDetailLabel, setHistoriqueDetailLabel] = useState(I18n.t('SOINS'));
    const [loadMore, setLoadMore] = useState(false);
    const [historyResult, setHistoryResult] = useState([]);
    const [wallet] = useState(store.getState().walletDetailReducer.result.response);


    let dropDownAlertRef: any = null;

    function useForceUpdate() {
        const [value, setValue] = useState(0); // integer state
        return () => setValue(value => value + 1); // update the state to force render
    }
    const forceUpdate = useForceUpdate();


    useEffect(() => {
        dispatch(fetchGetConsultationReset());
        dispatch(fetchAcceptRejectConsultationReset());
        readUser().then((user) => {
            setUser(user);
            console.log("User", user);
            fetchGetConsultation('', 'ALL', '', `&network_id=${wallet.id_network}&network_agent_id=${wallet.network_agent_id}&pagination=true&page=1`);
        });
    }, []);

    useEffect(() => {

        if (getConsultation.result !== null) {

            if (page < getConsultation.result.response.last_page)
                setHistoryResult(historyResult.concat(getConsultation.result.response.data));

            if (page === getConsultation.result.response.last_page) {
                console.log("Page", page === getConsultation.result.response.last_page);
                setPage(page + 1);
                console.log("historyResult.concat", historyResult.concat(getConsultation.result.response.data));
                setHistoryResult(historyResult.concat(getConsultation.result.response.data));
            }
        }

        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());*/
        }
        //forceUpdate();
    }, [getConsultation]);

    useEffect(() => {
        console.log("historyResult", historyResult);
    }, [historyResult]);

    /*    useEffect(() => {
            if (acceptRefuseConsultation.result !== null) {
                if(loadMore)
                setHistoryResult(historyResult.concat(acceptRefuseConsultation.result.data.data.content));
            }

            if (acceptRefuseConsultation.error) {
                dropDownAlertRef.alertWithType(
                    'error',
                    I18n.t('ERROR_LABEL'),
                    Utils.getErrorMsg(acceptRefuseConsultation),
                );
                dispatch(fetchAcceptRejectConsultationReset());
                setDisplayModalHistory(false);
                if (user !== null)
                    fetchGetConsultation(user.id, 'UNTREATED');
            }
        }, [acceptRefuseConsultation]);*/

    const handleLoadMore = () => {
        dispatch(fetchGetConsultationReset());
        fetchGetConsultation('', 'ALL', '', `&network_id=${wallet.id_network}&network_agent_id=${wallet.network_agent_id}&pagination=true&pagination=true&page=${page + 1}`);
        setPage(page + 1);
    }

    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 renderFooterLoader = () => {

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

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

    const renderModalHistoryDetail = () => (
        <Dialog.Container useNativeDriver={true} visible={displayModalHistory}>

            <Dialog.Title>{I18n.t('DETAIL') + ' ' + historiqueDetailLabel}</Dialog.Title>

            {historyItemDetail.hasOwnProperty('exams') ?

                <ScrollView persistentScrollbar={true}>
                    <View style={[styles.blockView, {borderBottomColor: Color.borderColor}]}>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('NETWORK')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.network.name}</Text>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('PATIENT')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{`${historyItemDetail.patient_lastname !== null ? historyItemDetail.patient_lastname : null} ${historyItemDetail.patient_firstname !== null ? historyItemDetail.patient_firstname : ''}`}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>Situation</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.patient_situation.toLowerCase()}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('PRATICIEN')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{`${historyItemDetail.practitioner_lastname} ${historyItemDetail.practitioner_firstname}`}</Text>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('MONTANT_ASSURANCE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.insurance_amount}</Text>
                            </View>
                        </View>


                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('MONTANT_ASSURE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.insured_amount}</Text>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('CLASSE_PRESTATAIRE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{uppercaseFirstLetter(historyItemDetail.practitioner_provider_class.toLowerCase())}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('STATE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{uppercaseFirstLetter(historyItemDetail.state.toLowerCase())}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>Type</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{uppercaseFirstLetter(historyItemDetail.type.toLowerCase())}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('CONDITION_PRISE_CHARGE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{uppercaseFirstLetter(historyItemDetail.care_condition.toLowerCase())}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('INSTITUTE_NAME')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{uppercaseFirstLetter(historyItemDetail.institution_name.toLowerCase())}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>Date</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{moment(historyItemDetail.created_at).format('YYYY-MM-DD')}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('PRESTATION')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                {historyItemDetail.performances.map(performance => (
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${performance.act.name} \n ${performance.amount_formatted} ${!isNil(performance.home_visit_fees_formatted) ? '\n' + I18n.t('FRAIS_DEPLACEMENT')+': ' + performance.home_visit_fees_formatted : ''} \n${!isNil(performance.unit_price_formatted) ? 'P.U: ' + performance.unit_price_formatted + '\n P.T: ' +performance.total_price : ''}`}</Text>
                                ))}
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('EXAMEN')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                {historyItemDetail.exams.map(exam => (
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${exam.quantity} ${exam.description} \n ${exam.act.name} \n ${!isNil(exam.unit_price_formatted) ? 'P.U: ' + exam.unit_price_formatted + '\n P.T: ' + exam.total_price : ''}`}</Text>
                                ))}
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('MEDICAMENT')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                {historyItemDetail.prescriptions.map(prescription => (
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${prescription.quantity} ${prescription.drug_or_device.name} \n ${prescription.dosage} \n ${!isNil(prescription.unit_price_formatted) ? 'P.U: ' + prescription.unit_price_formatted + '\n P.T: ' + prescription.total_price : ''}`}</Text>
                                ))}
                            </View>
                        </View>

                    </View>
                </ScrollView>
                :
                'health_care_sheet_id' in historyItemDetail ?
                    <ScrollView persistentScrollbar={true}>
                        <View style={[styles.blockView, {borderBottomColor: Color.borderColor}]}>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>ID</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.id}</Text>
                                </View>
                            </View>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('NETWORK')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.network.name}</Text>
                                </View>
                            </View>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('ACTE')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.act_name}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('STATUS')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.state.toLowerCase()}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('BENEFICIARY')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${historyItemDetail.user_firstname !== null ? historyItemDetail.user_firstname : ''} ${historyItemDetail.user_lastname !== null ? historyItemDetail.user_lastname  : ''}`}
                                    </Text>
                                </View>
                            </View>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('EMAIL')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.user_email}</Text>
                                </View>
                            </View>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('PHONE')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.user_phone}</Text>
                                </View>
                            </View>


                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('EMETTEUR')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${historyItemDetail.issuer_agent_lastname !== null ? historyItemDetail.issuer_agent_lastname : ''} ${historyItemDetail.issuer_agent_firstname !== null ? historyItemDetail.issuer_agent_firstname  : ''}`}</Text>
                                </View>
                            </View>

                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('PHONE_EMETTEUR')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.issuer_agent_phone}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('AGENT_VALIDEUR')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{`${historyItemDetail.validating_agent_lastname !== null ? historyItemDetail.validating_agent_lasstname : ''} ${historyItemDetail.validating_agent_firstname !== null ? historyItemDetail.validating_agent_firstname  : ''}`}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('AGENT_VALIDEUR_EMAIL')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.validating_agent_email}</Text>
                                </View>
                            </View>
                            <View style={{flexDirection: 'row', marginTop: 10}}>
                                <View style={{flex: 1}}>
                                    <Text style={[styles.body2]}>{I18n.t('AGENT_VALIDEUR_PHONE')}</Text>
                                </View>
                                <View style={{flex: 1, alignItems: 'flex-end'}}>
                                    <Text
                                        style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.validating_agent_phone}</Text>
                                </View>
                            </View>

                        </View>
                    </ScrollView>

                    :
                <ScrollView persistentScrollbar={true}>
                    <View style={[styles.blockView, {borderBottomColor: Color.borderColor}]}>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('INVOICE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <TouchableOpacity onPress={()=>{
                                    setDisplayModalHistory(!displayModalHistory);
                                    navigation.push('PDFViewerScreen', {url: `${historyItemDetail.file_url}`, title: ''});
                                }}>
                                    <Text style={{color: "blue", textDecorationLine: 'underline', fontWeight: 'bold'}}>Facture.PDF</Text>
                                </TouchableOpacity>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>{I18n.t('INVOICE_ID')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.invoice_id}</Text>
                            </View>
                        </View>

                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text style={[styles.body2]}>Date</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.created_at}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('AMOUNT')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.amount}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('MONTANT_ASSURANCE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.insured_amount}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('MONTANT_ASSURE')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.insurer_amount}</Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', marginTop: 10}}>
                            <View style={{flex: 1}}>
                                <Text tyle={[Typography.body2]}>{I18n.t('INSTITUTE_NAME')}</Text>
                            </View>
                            <View style={{flex: 1, alignItems: 'flex-end'}}>
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{historyItemDetail.institution_name}</Text>
                            </View>
                        </View>
                        {
                            historyItemDetail.health_care_sheets.map((history_care) => (
                                <View style={{flexDirection: 'row', marginTop: 10}}>
                                    <AccordionComponent
                                        title={I18n.t('FEUILLE_SOIN')}
                                        description={`${I18n.t('ID')}: ${history_care.health_care_sheet_id}\
                                                        ${I18n.t('AMOUNT')}: ${history_care.amount}\
                                                        ${I18n.t('MONTANT_ASSURANCE')}: ${history_care.insurerAmount}\
                                                        ${I18n.t('MONTANT_ASSURE')}: ${history_care.insuredAmount}\
                                                        ${I18n.t('PATIENT')}: ${history_care.patient_firstname !== null ? history_care.patient_firstname : '' } ${history_care.patient_lastname !== null ? history_care.patient_lastname : ''}\n
                                                        ${I18n.t('PRATICIEN')}: ${history_care.practitioner_firstname !== null ? history_care.practitioner_firstname : ''} ${history_care.practitioner_lastname}\
                                                        `}
                                        open
                                        style={{marginTop: 20, marginBottom: 10}}
                                    />
                                </View>
                            ))
                        }
                    </View>
                </ScrollView>}

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

            {/*            <Dialog.Button bold={true} label={I18n.t('REJECT')} onPress={() => {
                fetchAcceptRejectConsultation({
                    health_care_sheet_id: historyItemDetail.id,
                    user_id: user.id,
                    action: "REJECT"
                });
            }}/>

            <Dialog.Button bold={true} label={I18n.t('ACCEPT')} onPress={() => {
                fetchAcceptRejectConsultation({
                    health_care_sheet_id: historyItemDetail.id,
                    user_id: user.id,
                    action: "ACCEPT"
                });
            }}/>*/}

        </Dialog.Container>
    )


    const renderItem = (item) => (
        item.hasOwnProperty('exams') ?
            <TouchableOpacity
                style={[styles.content, {backgroundColor: Color.cardBackgroundColor}]}
                onPress={() => {
                    setDisplayModalHistory(true);
                    setHistoryItemDetail(item);
                    /*navigation.navigate('validateConsultationDetailScreen', {
                        item
                    });*/
                }}>
                <View style={[styles.contentTop, {borderColor: Color.borderColor}]}>
                    <View style={{flex: 1, alignItems: 'flex-start'}}>
                        <Text caption1>{`${I18n.t('MONTANT_ASSURANCE')}: ${item.insurance_amount}`}</Text>
                        <Text footnote light numberOfLines={1}>
                            {`${I18n.t('STATE')}: ${item.state.toLowerCase()}`}
                        </Text>
                    </View>
                    <View style={{flex: 1, alignItems: 'flex-end'}}>
                        <Text
                            caption1>{`${I18n.t('NETWORK')}: ${item.network.name}`}</Text>
                        <Text footnote light numberOfLines={1}>
                            {`${I18n.t('BENEFICIARY')}: ${item.patient_firstname !== null ? item.patient_firstname : ''} ${item.patient_lastname !== null ? item.patient_lastname  : ''}\ (${item.patient_situation.toLowerCase()})`}
                        </Text>
                    </View>

                </View>
                <View style={styles.contentBottom}>
                    <View style={styles.bottomLeft}>
                        <View style={{marginHorizontal: 5}}>
                            <Text caption1 semibold accentColor>
                                {`Type: ${item.type.toLowerCase()}`}
                            </Text>
                        </View>
                    </View>
                    <View style={{flexDirection: 'row', alignItems: 'flex-end'}}>
                        <Text caption1 semibold primaryColor>
                            {`Date: ${moment(item.created_at).format('YYYY-MM-DD')}`}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
            : 'health_care_sheet_id' in item ?
                <TouchableOpacity
                    style={[styles.content, {backgroundColor: Color.cardBackgroundColor}]}
                    onPress={() => {
                        setDisplayModalHistory(true);
                        setHistoryItemDetail(item);
                        /*navigation.navigate('validateConsultationDetailScreen', {
                            item
                        });*/
                    }}>
                    <View style={[styles.contentTop, {borderColor: Color.borderColor}]}>
                        <View style={{flex: 1, alignItems: 'flex-start'}}>
                            <Text caption1>{`${I18n.t('ACTE')}: ${item.act_name}`}</Text>
                            <Text footnote light numberOfLines={1}>
                                {`${I18n.t('EMETTEUR')}: ${item.issuer_agent_lastname}`}
                            </Text>
                        </View>
                        <View style={{flex: 1, alignItems: 'flex-end'}}>
                            <Text
                                caption1>{`${I18n.t('NETWORK')}: ${item.network.name}`}</Text>
                            <Text footnote light numberOfLines={1}>
                                {`${I18n.t('BENEFICIARY')}: ${item.user_firstname !== null ? item.user_firstname : ''} ${item.user_lastname !== null ? item.user_lastname  : ''}`}
                            </Text>
                        </View>

                    </View>
                    <View style={styles.contentBottom}>
                        <View style={styles.bottomLeft}>
                            <View style={{marginHorizontal: 5}}>
                                <Text caption1 semibold accentColor>
                                    {`${I18n.t('STATUS')}: ${item.state}`}
                                </Text>
                            </View>
                        </View>
                        <View style={{flexDirection: 'row', alignItems: 'flex-end'}}>
                            <Text caption1 semibold primaryColor>
                                {`Date: ${moment(item.created_at).format('YYYY-MM-DD')}`}
                            </Text>
                        </View>
                    </View>
                </TouchableOpacity>
            :
                <TouchableOpacity
                    style={[styles.content, {backgroundColor: Color.cardBackgroundColor}]}
                    onPress={() => {
                        setDisplayModalHistory(true);
                        setHistoryItemDetail(item);
                        /*navigation.navigate('validateConsultationDetailScreen', {
                            item
                        });*/
                    }}>
                    <View style={{borderColor: Color.borderColor, flexDirection: "row",paddingBottom: 10, borderBottomWidth: 0.5}}>
                        <View style={{flex: 1, alignItems: 'flex-start'}}>
                            <Text caption1>{`${I18n.t('AMOUNT')}: ${item.amount}`}</Text>
                        </View>
                    </View>
                    <View style={[styles.contentTop, {borderColor: Color.borderColor}]}>
                        <View style={{flex: 1, alignItems: 'flex-start'}}>
                            <Text
                                caption1>{`${I18n.t('MONTANT_ASSURANCE')}: ${item.insurer_amount}`}</Text>
                            <Text footnote light numberOfLines={1}>
                                {`${I18n.t('MONTANT_ASSURE')}: ${item.insured_amount}`}
                            </Text>
                        </View>

                    </View>
                    <View style={styles.contentBottom}>
                        <View style={{flexDirection: 'row', alignItems: 'flex-start'}}>
                            <Text caption1 semibold primaryColor>
                                {`Date: ${moment(item.created_at).format('YYYY-MM-DD')}`}
                            </Text>
                        </View>
                    </View>
                </TouchableOpacity>
    );

    return (
        <ScreenComponent>
            <DropdownAlert ref={ref => (dropDownAlertRef = ref)}/>
            <View style={styles.contain}>

                <View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingBottom: 10}}>
                    <Tag primary
                         icon={<FontAwesome5 name='book-medical' size={20} color={Color.whiteColor}
                                             style={{marginLeft: 15}}/>}
                         style={{
                             paddingRight: 10,
                             width: 120,
                             borderTopRightRadius: 0,
                             borderBottomRightRadius: 0,
                             borderRightWidth: 1,
                             borderRightColor: Color.whiteColor
                         }}
                         onPress={() => {
                             dispatch(fetchGetConsultationReset());
                             setPage(1);
                             setLoadMore(false);
                             setHistoryResult([]);
                             setHistoriqueDetailLabel(I18n.t('SOINS'));
                             fetchGetConsultation('', 'ALL', '', `&network_id=${wallet.id_network}&network_agent_id=${wallet.network_agent_id}&pagination=true&page=1`);

                         }}>
                        {`   ${I18n.t('SOINS')}`}
                    </Tag>
                    <Tag icon={<MaterialCommunityIcons name='file' size={20} color={Color.whiteColor}/>}
                         style={{width: 110, borderTopLeftRadius: 0, borderBottomLeftRadius: 0, borderTopRightRadius: 0, borderBottomRightRadius: 0,}}
                         primary
                         onPress={() => {
                             dispatch(fetchGetConsultationReset());
                             setPage(1);
                             setLoadMore(false);
                             setHistoryResult([]);
                             setHistoriqueDetailLabel(I18n.t('AUTORISATION_SOIN'));
                             fetchGetDemandeAutorisationSoin(`?network_id=${wallet.id_network}&network_agent_id=${wallet.network_agent_id}&page=1&perPage=20`);
                         }}>
                        {` ${I18n.t('AUTORISATION_SOIN')}`}
                    </Tag>
                    <Tag icon={<MaterialCommunityIcons name='file' size={20} color={Color.whiteColor}/>}
                         style={{width: 110, borderTopLeftRadius: 0, borderBottomLeftRadius: 0,}}
                         primary
                         onPress={() => {
                             dispatch(fetchGetConsultationReset());
                             setPage(1);
                             setLoadMore(false);
                             setHistoryResult([]);
                             setHistoriqueDetailLabel(I18n.t('INVOICE'));
                             fetchGetInvoiceHistory(`?network_id=${wallet.id_network}&network_agent_id=${wallet.network_agent_id}&page=1&perPage=20`, false);
                         }}>
                        {` ${I18n.t('INVOICE')}`}
                    </Tag>

                </View>


                {getConsultation.loading && !loadMore
                    ? renderLoader()
                    : (
                        <FlatList
                            style={{flex: 1}}
                            ListEmptyComponent={() => {
                                return (
                                    <Text>{I18n.t('NO_WALLET_HISTORY')}</Text>
                                )
                            }}
                            data={historyResult}
                            keyExtractor={(item, index) => item.id}
                            renderItem={({item, index}) => (
                                renderItem(item)
                            )}
                            onEndReached={() => {
                                if (getConsultation.result !== null) {
                                    if (page < getConsultation.result.response.last_page) {
                                        setLoadMore(true);
                                        handleLoadMore();
                                    }
                                }
                            }}
                            onEndReachedThreshold={0.5}
                            ListFooterComponent={getConsultation.result !== null ? page < getConsultation.result.response.last_page ? renderFooterLoader() : null : null}
                        />
                    )}
                {displayModalHistory && renderModalHistoryDetail()}
            </View>
        </ScreenComponent>
    )
};

const mapStateToProps = createStructuredSelector({
    subscriptionList: selectSubscriptionList,
    activatePaySubscription: selectActivatePaySubscription,
    getConsultation: selectGetConsultation,
    acceptRefuseConsultation: selectAcceptRefuseConsultation
});

export default connect(mapStateToProps, {
    fetchActivePaySubscription,
    fetchGetConsultation,
    fetchAcceptRejectConsultation,
    fetchGetSubscription,
    fetchGetDemandeAutorisationSoin,
    fetchGetInvoiceHistory

})(
    HistoriqueNanoSanteAgentScreen,
);
const styles = StyleSheet.create({
    textInput: {
        height: 46,
        backgroundColor: Color.fieldColor,
        borderRadius: 5,
        marginTop: 10,
        padding: 10,
        width: '100%',
    },
    contentService: {
        paddingVertical: 10,
        borderBottomWidth: 0.5,
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'space-between',
    },
    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,
    },
});
