import React, {useEffect} from 'react'
import { connect } from 'react-redux'
import { useParams } from "react-router-dom"
import { decryptURIparams } from '../../utility/Utils'
import WithSpinner from "../../utility/hoc/spinner/with-spinner.component"
import {  MedicalLogTypes } from "../../../redux/dashboard/medical-logs/medical-logs.action.types"
import { fetchMedicalLogsAsync, fetchMedicalLogReportAsync, clearGetMedicalLogState  } from "../../../redux/dashboard/medical-logs/medical-logs.action"
import CaseHistory from "../../case-history/case-history.component"
import CaseHistoryTemplateDocument from "../../case-history/case-history.report.template"
import { exportToPdf } from '../../utility/Utils'
import {MettaSvr_Common} from '../../../redux/helpers/action-enums'

import './case-history.styles.scss'

const CaseHistoryViewerComponent = (props) => {

    const { patientId } = useParams()

    const { inProgress, reportResult, medicalLogReportDownloadInProgress, theUser,
        doFetchMedicalLogs, doFetchMedicalLogReport, doClearMedicalLog} = props
    
    useEffect(() => {
        return () => {
            doClearMedicalLog()
        }
    },[])

    useEffect (() => {   
        const targetPatientId = decryptURIparams(patientId)
        doFetchMedicalLogs(targetPatientId ?? theUser.patientUserId ?? theUser.userId)
    },[theUser])

    const submitReport = () => { 
        const thePatientId = decryptURIparams(patientId)       
        doFetchMedicalLogReport( thePatientId ?? theUser.patientUserId ?? theUser.userId )
    }
     
    useEffect(() => {
        if(!!reportResult){
            exportToPdf({apiData: reportResult, fileName: MettaSvr_Common.FILE_NAMES.PatientMedicalHistoryReport,
                template: <CaseHistoryTemplateDocument data={reportResult}/>
            })
        }
    },[reportResult])

    const CaseHistoryWithSpinner = WithSpinner(CaseHistory)
    
    // console.log(`⚠️ ${submissionErrorMessage}`)
    return (
        <>        
            <CaseHistoryWithSpinner defaultHeight={false} isLoading={inProgress} {...props}
                onSubmitReport={submitReport} reportIsLoading={medicalLogReportDownloadInProgress}/>            
        </>
    )
        
}



const mapStateToProps = ({user,caseHistory}) => ({
    theUser:user.currentUser,
    submissionErrorMessage: caseHistory.errorMessages,
    initialValues: caseHistory.result,
    inProgress: caseHistory.inProgress,
    readOnly: true,
    medicalLogReportDownloadInProgress: caseHistory.medicalLogReportDownloadInProgress, 
    reportResult: caseHistory.medicalLogReportResult,
    isEducator: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Educator
  })
  
  const mapDispatchToProps = dispatch => ({
    doFetchMedicalLogs: (patientId) => dispatch(fetchMedicalLogsAsync(patientId)),
    doFetchMedicalLogReport: (patientId) => dispatch(fetchMedicalLogReportAsync(patientId)),
    doClearMedicalLog: () => dispatch(clearGetMedicalLogState()),
    doDismissError: () => dispatch({
        type: MedicalLogTypes.MEDICAL_LOG_RESET_STATE
      })
  })
export default connect(mapStateToProps, mapDispatchToProps)(CaseHistoryViewerComponent)