import React, { useEffect, useState } from 'react'
import { connect } from "react-redux"

import { fetchPatientListsAsync, clearGetPatientListState,clearPatientListErrorState, 
    updatePatientStatusAsync, setTargetPatientToUpdate } from "../../../redux/dashboard/patient-list/patient-list.action"
import { MettaSvr_Common } from "../../../redux/helpers/action-enums"
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component";
import GenericModalComponent from '../../utility/hoc/modal-views/generic.modal.component'
import {  getPatientList, getPatientListIsFetching, getTotalItems, getErrorMessage,
    getGetIsDoctor, getIsSaving, getUpdateIndex, getSavedResult, getGetIsEducator
} from '../../../redux/dashboard/patient-list/selectors'
import DataTable from "../../data-table/data-table.component"
import {rowformatterForDoctor, headersDoctor } from './datatable.intializers'
import './doctor-persona-list.styles.scss'
import {menuItems, menuItemsForEducator, ActionType} from './default-menu-items'
import ToastComponent from "../../utility/toast/toast.component";
import UpdatePatientCriticalityStatusComponent from './child-views/update-criticality-status.component'

const PatientListComponent = ({ isDoctor, isEducator, patients, loading, errorMessage, totalItems, wipIndex,isSubmitting,
    doFetchPatients, doClearAll, doUpdatePatientStatus, doClearErrors, doSetupTargetPatient, savedResult
}) => {

    const [showCriticalityModal, setShowCriticalityModal] = useState(false)
    
    useEffect(() => {
        doFetchPatients()
        return () => {
            doClearAll()
        }
    }, [])

    useEffect(() =>{
        if(!!savedResult){
            dismissUpdateCriticalStateModal()
        }
    },[savedResult])

    const doPageChanged = (pageNumber) => {
        doFetchPatients(pageNumber)
    }

    const menuItemClicked = (identifier, wipIndex, actionType) => {
        console.log(actionType)
        if(actionType === ActionType.DEACTIVATE_USER){
            doUpdatePatientStatus(identifier, wipIndex, false)
        }else if(actionType === ActionType.ACTIVATE_USER){
            doUpdatePatientStatus(identifier, wipIndex, true)

        }else{
            doSetupTargetPatient({identifier, index: wipIndex})
            setShowCriticalityModal(true)
        }
    }

    const dismissUpdateCriticalStateModal = () => {  
        doSetupTargetPatient({identifier: null, index : -1})      
        setShowCriticalityModal(false)
        // clearAll()
    }

    return (
        <WrapperPanelComponent>
            <div>
                <DataTable showControlsPerRow={true} 
                            rowMenu={
                                isEducator ?
                                menuItemsForEducator(patients, menuItemClicked) :
                                menuItems(patients, menuItemClicked)
                            }
                            // rowFormatters={isDoctor ? rowformatterForDoctor(patients) : rowformatterForEducator(patients)}
                            rowFormatters={rowformatterForDoctor(patients)}
                            data={patients}
                            // headers={isDoctor ? headersDoctor : headersEducator}
                            headers={ headersDoctor}
                            isLoading={loading}
                            idField="SubsCode"
                            showRowLoading={isSubmitting}
                            workingAtRow={wipIndex}
                            totalItems={totalItems}
                            itemsPerPage={ MettaSvr_Common.ITEMS_PER_PAGE }
                            onPageChangeHandler={doPageChanged}
                        />                  
                

        </div>
        { !!errorMessage && !showCriticalityModal ? <ToastComponent message={errorMessage} onclose={doClearErrors}/> : null }
        <GenericModalComponent
                    show={showCriticalityModal}
                    onHide={dismissUpdateCriticalStateModal}
                    title={"Update Criticallity Status"}
                >
                  <UpdatePatientCriticalityStatusComponent />  
            </GenericModalComponent>
        </WrapperPanelComponent>
    )
}

const mapStateToProps = (state) => ({
    patients: getPatientList(state),
    loading: getPatientListIsFetching(state),
    errorMessage: getErrorMessage(state),
    totalItems: getTotalItems(state),
    isDoctor: getGetIsDoctor(state),
    isEducator: getGetIsEducator(state),
    wipIndex: getUpdateIndex(state),
    isSubmitting: getIsSaving(state),
    savedResult: getSavedResult(state)
})

const mapDispatchToProps = dispatch => ({
    doFetchPatients: (page = 1) => dispatch(fetchPatientListsAsync(page)),
    doUpdatePatientStatus: (patientId, wipIndex, status) => dispatch(updatePatientStatusAsync({
        UserId: patientId,
        IsActive: status,
        indexOfRecord: wipIndex
    })),
    doClearErrors: () => dispatch(clearPatientListErrorState()),
    doSetupTargetPatient: (body) => dispatch(setTargetPatientToUpdate(body)),
    doClearAll: () => dispatch(clearGetPatientListState())
})
export default connect(mapStateToProps, mapDispatchToProps)(PatientListComponent)