import React, { useEffect, useState } from 'react'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { connect } from 'react-redux'
import { useParams } from "react-router-dom"
import DataTable from "../../data-table/data-table.component"
import {rowformatter, headers} from './datatable.intializers'
import { getLabReportIsFetching, getLabReportList,  getErrorMessage, getGetIsPatient, getGetIsDoctor, getCurrentUserId,
    getTotalItems, getSavedResult, getLabReportDownloadSavedResult, getLabReportDownloadInProgress } from '../../../redux/dashboard/lab-report/selectors'
import { fetchLabReportListStart, clearLabReportListErrorState, 
    createLabReportStart, clearLabReportState, downloadLabReportStart} from '../../../redux/dashboard/lab-report/lab-report.action'
import ToastComponent from "../../utility/toast/toast.component"
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component";
import GenericModalComponent from '../../utility/hoc/modal-views/generic.modal.component'
import { decryptURIparams } from '../../utility/Utils'
import { MettaSvr_Common } from "../../../redux/helpers/action-enums"
import { exportToExcel, exportToPdf } from '../../utility/Utils'
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import LabReportTemplateDocument from './child-views/lab-report.report.template'

import AddLabReportComponent from './child-views/add-lab-report.component'
import './lab-reports.styles.scss'

const ReportColumns = ["PatientName","EducatorName","TestDate","TestName","Value","LabTestStatusIndicatorVal","Comments"]

const LabReportComponent = props => {
    const {labReportList, loading,  errorMessage, isPatient,totalItems, savedResult, userId, isDoctor, downloadReportResult, downloadReportInProgress,
        doFetchLabReports,doClearErrorState,doClearAll, doFetchDownloadLabReports,
        ...restProps} = props

    const [showAddLabReportModal, setShowAddLabReportModal ] = useState(false)

    const dismissAddLabReportModal = () => {
        setShowAddLabReportModal(false)
        doClearErrorState()
    }
    const { patientId } = useParams()

    useEffect(() => {
        doFetchLabReports(decryptURIparams(patientId))
        return () =>{
            doClearAll()
        }
    },[])
    
    useEffect(() => {
        if(!!savedResult){
            dismissAddLabReportModal()
            doFetchLabReports(decryptURIparams(patientId))
        }
    },[savedResult])

    useEffect(() => {
        if(!!downloadReportResult){
            if(isDoctor){
                exportToExcel({apiData: !!downloadReportResult[0] ? downloadReportResult[0].LabReport : [], fileName: MettaSvr_Common.FILE_NAMES.PatientLabReport})                
            }else{
                exportToPdf({apiData: downloadReportResult, fileName: MettaSvr_Common.FILE_NAMES.PatientLabReport, template: <LabReportTemplateDocument data={downloadReportResult}/>})
            }
        }
    },[downloadReportResult])

    const submitReport = () => {   
        if(!isPatient){ // doctor + educator
            doFetchDownloadLabReports(decryptURIparams(patientId))
        }else{
            doFetchDownloadLabReports(decryptURIparams(userId))
        }     
        
    }

    const doPageChanged = (pageNumber) => {
        doFetchLabReports(decryptURIparams(patientId), pageNumber)
    }


    const ButtonWithSpinner = WithSpinner(
        () =>
          (
            <div className="d-flex justify-content-end">            
                <div className="shadow-sm p-1 bg-white rounded">
                    <button type="button" className="btn-login" onClick={submitReport}>
                    <FontAwesomeIcon size="2x" icon={`${ isDoctor ? 'file-excel' : 'file-pdf'}`}/></button>
                    {/* <FontAwesomeIcon size="2x" icon='file-excel'/></button> */}
                </div>                 
            </div>
        )
    )

    return (
        <WrapperPanelComponent>
            <div className="tabbable-line">
                <DataTable showControlsPerRow={false} 
                    rowFormatters={rowformatter(labReportList)}
                    data={labReportList}
                    headers={headers}
                    isLoading={loading}
                    idField="LabReportId"
                    totalItems={totalItems}
                    itemsPerPage={ MettaSvr_Common.ITEMS_PER_PAGE }
                    onPageChangeHandler={doPageChanged}
                    />  
            {
                isPatient || isDoctor ? 
                    <div className="pt-4">
                        <button className="btn-login" onClick={e => setShowAddLabReportModal(true)}>+ Add Lab Report</button>                                  
                    </div>
                : null    
            }
            {
                isDoctor || isPatient ?
                <ButtonWithSpinner defaultHeight={false} isLoading={downloadReportInProgress}/> :null
            }
            </div>
            { !!errorMessage  && !showAddLabReportModal ? <ToastComponent message={errorMessage} onclose={doClearErrorState}/> : null }

            <GenericModalComponent
                    show={showAddLabReportModal}
                    onHide={dismissAddLabReportModal}
                    title={"Add Lab Report"}
                >
                  <AddLabReportComponent forPatient={!!patientId ? decryptURIparams(patientId) : userId}/>  
            </GenericModalComponent>
        </WrapperPanelComponent>
    
    )
}
 

const mapStateToProps = state => ({
    userId: getCurrentUserId(state),
    labReportList: getLabReportList(state),
    loading: getLabReportIsFetching(state),
    errorMessage: getErrorMessage(state),
    isPatient: getGetIsPatient(state),
    isDoctor: getGetIsDoctor(state),
    totalItems: getTotalItems(state),
    savedResult: getSavedResult(state),
    downloadReportResult: getLabReportDownloadSavedResult(state), 
    downloadReportInProgress: getLabReportDownloadInProgress(state)
})

const mapDispatchToProps = dispatch => ({
    doFetchLabReports: (patientId, page = 1) => dispatch(fetchLabReportListStart({patientId, page})),
    doFetchDownloadLabReports: (patientId, page = 1) => dispatch(downloadLabReportStart({patientId, columns: ReportColumns, page})),
    doCreateLabReport: (patientId) => dispatch(createLabReportStart(patientId)),
    doClearErrorState: () => dispatch(clearLabReportListErrorState()),
    doClearAll: () => dispatch(clearLabReportState()),

})

export default connect(mapStateToProps, mapDispatchToProps)(LabReportComponent)