/**
 * Project iLinkWorld
 * File AcceptOrRejectConsultationScreen
 * Path screens/wallet/user
 * Created by BRICE ZELE
 * Date: 01/12/2021
 */
import React, {useEffect, useState} from 'react';
import {
    ActivityIndicator,
    Alert,
    Dimensions,
    FlatList,
    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,
    fetchGetConsultation,
    fetchGetConsultationReset
} 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";


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

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

const ValidateConsultationScreen = ({
                                        navigation,
                                        fetchGetConsultation,
                                        fetchAcceptRejectConsultation,
                                        getConsultation,
                                        acceptRefuseConsultation
                                    }) => {
    const dispatch = useDispatch();
    const [user, setUser] = useState(null);
    const [displayModalHistory, setDisplayModalHistory] = useState(false);
    const [historyItemDetail, setHistoryItemDetail] = useState({});

    let dropDownAlertRef: any = null;

    useEffect(() => {
        readUser().then((user) => {
            setUser(user);
            console.log("User", user);
            fetchGetConsultation(user.id, 'UNTREATED_ALL', '');
        });
        dispatch(fetchGetConsultationReset());
        dispatch(fetchAcceptRejectConsultationReset());
    }, []);

    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 (acceptRefuseConsultation.result !== null) {
            Alert.alert(
                I18n.t("SUCCESS"),
                acceptRefuseConsultation.result.response,
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchAcceptRejectConsultationReset());
                            setDisplayModalHistory(false);
                            if (user !== null)
                                fetchGetConsultation(user.id, 'UNTREATED_ALL', '');
                        }
                    }

                ],
                {cancelable: false}
            );
            if (user !== null)
                fetchGetConsultation(user.id, 'UNTREATED_ALL', '');
        }

        if (acceptRefuseConsultation.error) {
            Alert.alert(
                I18n.t("ERROR_LABLE"),
                Utils.getErrorMsg(acceptRefuseConsultation),
                [
                    {
                        text: I18n.t("OK"), onPress: () => {
                            dispatch(fetchAcceptRejectConsultationReset());
                            setDisplayModalHistory(false);
                            if (user !== null)
                                fetchGetConsultation(user.id, 'UNTREATED_ALL', '');
                        }
                    }
                ],
                { cancelable: false }
            );
/*            dropDownAlertRef.alertWithType(
                'error',
                I18n.t('ERROR_LABEL'),
                Utils.getErrorMsg(acceptRefuseConsultation),
            );
            dispatch(fetchAcceptRejectConsultationReset());*/
        }
    }, [acceptRefuseConsultation]);

    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 renderModalHistoryDetail = () => (
        <Dialog.Container useNativeDriver={true} visible={displayModalHistory}>

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

            <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 : ''} ${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('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('EXAMEN')}</Text>
                        </View>
                        <View style={{flex: 1, alignItems: 'flex-end'}}>
                            {historyItemDetail.exams.map(exam => (
                                <Text
                                    style={[Typography.caption1, Color.grayColor]}>{`${exam.description} \n ${exam.act.name} \n`}</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.drug_or_device.name} \n ${prescription.dosage} \n`}</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} \n`}</Text>
                            ))}
                        </View>
                    </View>

                </View>
            </ScrollView>

            <Dialog.Button bold={true} label={I18n.t('CANCEL_LABEL')} 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) => (
        <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('NETWORK')}: ${item.network.name}`}</Text>
                </View>
            </View>

            <View style={[styles.contentTop, {borderColor: Color.borderColor}]}>
                <View style={{flex: 1, alignItems: 'flex-start'}}>
                    <Text caption1>{`${I18n.t('PATIENT')}: ${item.patient_lastname !== null ? item.patient_lastname : ''} ${item.patient_firstname !== null ? item.patient_firstname : ''}`}</Text>
                    <Text footnote light numberOfLines={1}>
                        {`${I18n.t('SITUATION')}: ${item.patient_situation.toLowerCase()}`}
                    </Text>
                </View>
                <View style={{flex: 1, alignItems: 'flex-end'}}>
                    <Text
                        caption1>{`${I18n.t('PRATICIEN')}: ${item.practitioner_lastname} ${item.practitioner_firstname}`}</Text>
                    <Text footnote light numberOfLines={1}>
                        {`${I18n.t('SITUATION')}: ${item.practitioner_provider_class}`}
                    </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>
    )

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

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

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

export default connect(mapStateToProps, {
    fetchActivePaySubscription,
    fetchGetConsultation,
    fetchAcceptRejectConsultation,

})(
    ValidateConsultationScreen,
);
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,
    },
});
