import React, {useEffect, useState, lazy} from 'react'
import { connect } from "react-redux"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { useParams } from "react-router-dom"
import DataTable from "../../data-table/data-table.component"
import {rowformatter, headers, dateFormatters, momentObjects} from './daily-logs.datatable.intializers'
import {fetchDailyLogsAsync, clearPostDailyLogState, fetchDailyLogReportAsync, clearGetDailyLogState} from '../../../redux/dashboard/daily-logs/daily-logs.action'
import {chatHubReset} from '../../../redux/dashboard/chat-box/chat-box.action'
import GenericModalComponent from '../../utility/hoc/modal-views/generic.modal.component'
import ToastComponent  from '../../utility/toast/toast.component'
import AddDailyLogComponent from "./child-views/add-daily-log.component"
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component"
import {MettaSvr_Common} from '../../../redux/helpers/action-enums'
import { decryptURIparams } from '../../utility/Utils'
import { exportToExcel, exportToPdf } from '../../utility/Utils'
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import DailyLogTemplateDocument from "./child-views/daily-logs.report.template"
import { getResult, getErrorMessage, getLoading, getRemoteSavedResult, getReportIsLoading,
getReportResult, getTotalItems
} from '../../../redux/dashboard/daily-logs/selectors'

import { getGetIsDoctor, getGetIsPatient, getGetIsVisitor, getCurrentUser, getIsSuperAdmin } from '../../../redux/user/selectors'
import './daily-logs.styles.scss'
import { ChatHubTypes } from "../../../redux/dashboard/chat-box/chat-box.action.types"


// const ReportColumns = ["LogDate","LogTime","LogTypeVal","Details","Comments","CriticalityStatusVal"]
const ChatBoxComponent = lazy(() => import("./chat-box/chat-box.component"))

const DailyLogComponent = ({user, reportResult, isSuperAdmin, isDoctor, isPatient, isVisitor, reportIsLoading, totalItems, result, remoteSavedResult, loading, errorMessage,
    fetchDailyLogs, clearAddDailyLog, clearDailyLogErrors, clearChat, fetchDailyLogReport, clearDailyLogState}) => {
//consists of patientId+suscriptionCode. From daily log action.
    const { extraParams } = useParams()
    const updatedExtraParams = decryptURIparams(extraParams)
    const [downloadExcel, setDownloadExcel] = useState(false)
    const [ fullScreenImageUrl, setFullScreenImageUrl ] =  useState(null)
    const [showAddDailyLog, setShowAddDailyLog ] = useState(false)
    const [showChatBox, setShowChatBox ] = useState(false)
    const [activeTab, setActiveTab ] = useState(momentObjects.today.format(dateFormatters.computeFormat))

    const todayComputed = momentObjects.today.format(dateFormatters.computeFormat)
    const yesterdayComputed = momentObjects.todayMinus1.format(dateFormatters.computeFormat)
    const dayBeforeYesterdayComputed = momentObjects.todayMinus2.format(dateFormatters.computeFormat)
    
    useEffect(()=>{
            const thePatientId = localDecodeURIparams(updatedExtraParams)?.patientId
            fetchDailyLogs(thePatientId ?? user.patientUserId ?? user.userId, activeTab)

            return () => {
                clearChat()
                clearDailyLogState()
            }
    }, [])
    
    useEffect(() => {
        if(!!reportResult){
            if(isDoctor && downloadExcel){
                exportToExcel({apiData: !!reportResult[0] ? reportResult[0].dailyLog : [], fileName: MettaSvr_Common.FILE_NAMES.PatientDailyLogReport})
                setDownloadExcel(false)
            }else{
                exportToPdf({apiData: reportResult, fileName: MettaSvr_Common.FILE_NAMES.PatientDailyLogReport,
                    template: <DailyLogTemplateDocument data={reportResult}/>
                })
                // exportToPdf({apiData: reportResult, fileName: MettaSvr_Common.FILE_NAMES.PatientDailyLogReport})
            }

        }
    }, [reportResult])
    //fire upon subsequent change in remote save result changes only
    useEffect(()=>{
        if(remoteSavedResult){
            const thePatientId = localDecodeURIparams(updatedExtraParams)?.patientId
            fetchDailyLogs(thePatientId ?? user.patientUserId ?? user.userId, activeTab)
            setShowAddDailyLog(false)
        }
    }, [remoteSavedResult])
    
    const tabChanged = (dateString) => {
        const thePatientId = localDecodeURIparams(updatedExtraParams)?.patientId
        fetchDailyLogs(thePatientId ?? user.patientUserId ?? user.userId, dateString)
        setActiveTab(dateString)
    }

    const dismissFullImageView = () => {
        setFullScreenImageUrl(null)
    }
    
    const dismissAddDailyLogs = () => {
        setShowAddDailyLog(false)
        clearAddDailyLog()
    }

    const localDecodeURIparams = (sourceString) => {
        if(!!sourceString){
            const [ patientId, subscriptionCode ] = decodeURIComponent(sourceString).split("+")
            return {patientId, subscriptionCode}
        }else{
            return null
        }
    }

    const closeChatBox = () => {
        clearChat()
        setShowChatBox(!showChatBox)
    }

    const doPageChanged = (pageNumber) => {
        const thePatientId = localDecodeURIparams(updatedExtraParams)?.patientId
        fetchDailyLogs(thePatientId ?? user.patientUserId ?? user.userId, activeTab, pageNumber)
    }

    const submitReport = (isExcel) => {        
        const thePatientId = localDecodeURIparams(updatedExtraParams)?.patientId
        fetchDailyLogReport( thePatientId ?? user.patientUserId ?? user.userId )
        setDownloadExcel(isExcel)
    
    }

    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={e => submitReport(false)}>
                    <FontAwesomeIcon size="2x" icon= 'file-pdf'/></button>
                </div>                 
                {
                    isDoctor ?
                        <div className="shadow-sm p-1 bg-white rounded">
                            <button type="button" className="btn-login" onClick={e => submitReport(true)}>
                            <FontAwesomeIcon size="2x" icon='file-excel'/></button>
                        </div>: null
                }
            </div>
        )
    )

    return (
        <>
            <WrapperPanelComponent>
                <div className="tabbable-line">
                            <ul className="nav nav-tabs ">
                                <li className={`${activeTab === todayComputed ? 'active': ''} p-3`} onClick={e => tabChanged(todayComputed)}>
                                        <i className="icon-calendar"></i>
                                        &nbsp;&nbsp;{momentObjects.today.format(dateFormatters.displayFormat)}
                                    
                                </li>
                                <li className={`${activeTab === yesterdayComputed ? 'active': ''} p-3`} onClick={e => tabChanged(yesterdayComputed)}>
                                        <i className="icon-calendar"></i>
                                        &nbsp;&nbsp;{momentObjects.todayMinus1.format(dateFormatters.displayFormat)}
                                    
                                </li>
                                <li className={`${activeTab === dayBeforeYesterdayComputed ? 'active': ''} p-3`} onClick={e => tabChanged(dayBeforeYesterdayComputed)}>
                                        <i className="icon-calendar"></i>
                                        &nbsp;&nbsp;{momentObjects.todayMinus2.format(dateFormatters.displayFormat)}
                                    
                                </li>
                            </ul>
                            <div className="tab-content">
                                <div className="tab-pane active" id="tab_default_1">
                                    <DataTable showControlsPerRow={false} 
                                        rowFormatters={rowformatter(result, setFullScreenImageUrl)}
                                        data={result}
                                        headers={headers}
                                        isLoading={loading}
                                        idField="DailylogId"
                                        totalItems={totalItems}
                                        itemsPerPage={ MettaSvr_Common.ITEMS_PER_PAGE }
                                        onPageChangeHandler={doPageChanged}
                                    />
                                </div>
                            </div>
                            {
                                isPatient ?
                                <div className="pt-4">
                                    <button className="btn-login" onClick={e => setShowAddDailyLog(true)}>+ Add New Log</button>                                  
                                </div>: null
                            }
                            {
                                isDoctor || isPatient ?
                                    <ButtonWithSpinner defaultHeight={false} isLoading={reportIsLoading}/> :
                                    null
                            }
                        </div>
                { !!errorMessage && !showAddDailyLog ? <ToastComponent message={errorMessage} onclose={clearDailyLogErrors}/> : null }
                <div className="fabs">
                    {
                        
                        showChatBox ? (<div className={`chat`} >
                                        <ChatBoxComponent subscriptionCode={localDecodeURIparams(updatedExtraParams)?.subscriptionCode}/>  
                                    </div> ) : null
                    }
                    {
                        !(isVisitor)?
                            <button className="fab" onClick={ closeChatBox }>
                                <i className={`prime fa ${showChatBox ? 'fa-close' : 'fa-comments-o'}`}></i>
                            </button> :
                        null

                    }
                </div>
                <GenericModalComponent
                    show={showAddDailyLog}
                    onHide={dismissAddDailyLogs}
                    title={"Add Daily Log"}
                >
                  <AddDailyLogComponent />  
                </GenericModalComponent>
                <GenericModalComponent
                    show={!!fullScreenImageUrl}
                    onHide={() => dismissFullImageView()}
                    title={"Full view"}
                >
                   {!!fullScreenImageUrl ? <img src={fullScreenImageUrl} className="fit-width" alt="no-image" /> : null }
                </GenericModalComponent>
            </WrapperPanelComponent>          
        </>
        )
}
 
const mapStateToProps = (state) => ({
    user: getCurrentUser(state),
    isDoctor: getGetIsDoctor(state),
    isPatient: getGetIsPatient(state),    
    isVisitor: getGetIsVisitor(state),   
    isSuperAdmin: getIsSuperAdmin(state), 
    result:  getResult(state),
    loading: getLoading(state),
    remoteSavedResult: getRemoteSavedResult(state),
    errorMessage: getErrorMessage(state),
    totalItems: getTotalItems(state),
    reportIsLoading: getReportIsLoading(state),
    reportResult: getReportResult(state)
})

const mapDispatchToProps = dispatch => ({
    fetchDailyLogs: (patientId, selectedDate, page = 1) => dispatch(fetchDailyLogsAsync(patientId, selectedDate, page)),
    fetchDailyLogReport: (query, page = 1) => dispatch(fetchDailyLogReportAsync(query,[],page)),
    clearChat: () => dispatch(chatHubReset()),
    clearAddDailyLog: () => dispatch(clearPostDailyLogState()),
    clearDailyLogErrors: () => dispatch(clearPostDailyLogState()),
    clearDailyLogState: () => dispatch(clearGetDailyLogState())
    
})


export default connect(mapStateToProps, mapDispatchToProps)(DailyLogComponent)
