import React , { useEffect, useState } from 'react'

import { connect } from "react-redux"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { MettaSvr_Common } from "../../../redux/helpers/action-enums"
import DataTable from "../../data-table/data-table.component"
import {rowformatter, headers} from './all-subscription-codes.datatable.intializers'
import {subscriptionActionType, menuItems, menuItemsForPatient} from './all-subscription-codes.menu.items'
import ToastComponent from "../../utility/toast/toast.component"
import EducatorListInPopover from './child-views/educatorlist-in-popover'
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component";
import { fetchSubscriptionCodeListAsync, clearGetSubscriptionCodeListState, 
    updateSubscriptionAsync, fetchSubscriptionCodeReportAsync } 
    from '../../../redux/dashboard/susbcription-code-list/susbcription-code-list.action'
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import { exportToExcel } from '../../utility/Utils'
import {startPatientRegistrationPayment, 
    registrationPaymentCapture, failedPatientRegistrationPayment,renewSubscriptionAsync,
    clearPatientRegistrationState, patientRegistrationClearState, cancelPatientRegistrationPayment
    } from '../../../redux/patient/patient.action'
import usePaymentEffect from "../../utility/effects/use-payment-fetch.effect"
import './all-subscription-codes.styles.scss'

const reportColumns = "SubsCode,PatientPublicId,PatientName,PatientDOB,PatientGender,PatientAddress,PatientEmail,PatientPhoneNo,DoctorPublicId,DoctorName,DoctorDOB,DoctorGender,DoctorAddress,DoctorEmail,DoctorPhoneNo,EducatorPublicId,EducatorName,EducatorDOB,EducatorGender,EducatorAddress,EducatorEmail,EducatorPhoneNo,SubsStartDate,SubsEndDate,CriticalityStatusInitialStr,CriticalityStatusFinalStr"

const AllSubscriptionCodeComponent = (props) => {

    const {
        subscriptions, loading, reportResult, errorMessage, reportIsLoading, renewSubscriptionErrorMessage, totalItems, isDoctor, isPatient, wipIndex, isSubmitting, paymentInProgress, result,
        fetchSubscriptions, fetchSubscriptionReport, clearSubscriptions, doUpdateSubscription, doRenewSubscription, clearRenewSubscriptionErrorAll, clearPatientRegistrationState, renewalFinishedSuccessfully
    } = props

    const[renewalUpdateIndex, setRenewalUpdateIndex] = useState(-1)
    const [cacheResult, setCacheResult] = useState(null)

    usePaymentEffect({...props, result: cacheResult})
    
    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={fetchSubscriptionReport}>
                    <FontAwesomeIcon size="2x" icon={"file-excel"}/></button>
                </div>
            </div>
        )
    )
    
    useEffect(() => {
        //renewal success end needs to get rid of row spinner 
        if(renewalFinishedSuccessfully){
            setRenewalUpdateIndex(-1)
        }
    },[renewalFinishedSuccessfully])

    useEffect(() => {
        fetchSubscriptions()
        return () =>{
            clearPatientRegistrationState()
            clearSubscriptions()
        }
    }, [])

        //First time when user registration completes and a new result with payment information
    //has come back as response from server.
    useEffect(() =>{
        setCacheResult(result)
    },[result])

    //This triggers everytime payment progress is set to false, when user cancels the payment dialog
    //or due to error in payment.
    useEffect(() => {
        if(!paymentInProgress){
            setRenewalUpdateIndex(-1)
            setCacheResult(null)
        }
    }, [paymentInProgress])

    //start saving the file if records present.
    useEffect(() => {
        if(!!reportResult){
            exportToExcel({apiData: reportResult, fileName: MettaSvr_Common.FILE_NAMES.SubscriptionReport})
        }
    },[reportResult])

    const doPageChanged = (pageNumber) => {
        fetchSubscriptions(pageNumber)
    }
    //renewal error end needs to get rid of row spinner 
    const closeRenewalErrorToast = () => {
        setRenewalUpdateIndex(-1)
        clearRenewSubscriptionErrorAll()
    }
    /**
     * 
     * @param {*} postEntity obejct includes SubscriptionId, EducatorId (optional), State (Optional), indexOfRecord 
     * (index in the current list of subscriptions), action type (deactivate action, renew action or change educator) 
     * @param {*} event : TBD
     */
    const menuItemClicked = (postEntity, event) => {
        if(postEntity.type === subscriptionActionType.RENEW){
            setRenewalUpdateIndex(postEntity.indexOfRecord)
            //if subscription already present then simply use it else send for renewal.
            if (!!props.result && !!props.result.userID){
                setCacheResult(props.result)
            }else{
                doRenewSubscription({subsCode: postEntity.subsCode}) 
            }
        }else if(postEntity.type === subscriptionActionType.CHANGE_EDUCATOR){
            doUpdateSubscription(postEntity)
        }
    }

    return (  
        <WrapperPanelComponent>
            <div>
                <DataTable showControlsPerRow={isPatient || isDoctor ? true : false} 
                        rowMenu={
                            isDoctor ? 
                                menuItems(subscriptions, menuItemClicked, (rowIndex, rowClickHandler) => <EducatorListInPopover itemRow={rowIndex} itemClickHandler={rowClickHandler}/>): 
                                menuItemsForPatient(subscriptions, menuItemClicked)
                        }
                        rowFormatters={rowformatter(subscriptions)}
                        data={subscriptions}
                        headers={headers}
                        isLoading={loading}
                        idField="SubscriptionId"
                        totalItems={totalItems}
                        workingAtRow={wipIndex > -1 ? wipIndex : renewalUpdateIndex}
                        showRowLoading={isSubmitting || (renewalUpdateIndex > -1 ? true : false)}                            
                        itemsPerPage={ MettaSvr_Common.ITEMS_PER_PAGE }
                        onPageChangeHandler={doPageChanged}
                    />                  
            
                { !!errorMessage ? 
                    <ToastComponent message={errorMessage } onclose={clearSubscriptions}/> :
                !!renewSubscriptionErrorMessage ? 
                    <ToastComponent message={renewSubscriptionErrorMessage} onclose={closeRenewalErrorToast}/> :
                renewalFinishedSuccessfully ? 
                    <ToastComponent success={true} message="Subscription renewed successfully" onclose={clearRenewSubscriptionErrorAll}/> 
                : null }
                {
                    isDoctor ? <ButtonWithSpinner defaultHeight={false} isLoading={reportIsLoading}/> 
                    : null
                }
            </div>

        </WrapperPanelComponent>
    )
}
 
const mapStateToProps = ({ user, subscriptionList, patientRegistration}) => ({
    result: patientRegistration.result,
    subscriptions: subscriptionList.result,
    loading: subscriptionList.inProgress,
    errorMessage: subscriptionList.errorMessages,
    renewSubscriptionErrorMessage: patientRegistration.errorMessages,
    totalItems: subscriptionList.recordCount,
    isDoctor: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Doctor,
    isPatient: user.currentUser.userType === MettaSvr_Common.UserTypeEnum.Patients,    
    wipIndex: subscriptionList.updateIndex,
    isSubmitting: subscriptionList.submissionInProgress,
    renewalFinishedSuccessfully: patientRegistration.paymentRenewalFinishedSuccessfully,
    reportIsLoading: subscriptionList.reportInProgress,
    reportResult: subscriptionList.reportResult,
    paymentInProgress: patientRegistration.paymentInProgress

})

const mapDispatchToProps = dispatch => ({
    fetchSubscriptions: (page = 1) => dispatch(fetchSubscriptionCodeListAsync(page)),
    fetchSubscriptionReport: (page = 1) => dispatch(fetchSubscriptionCodeReportAsync(reportColumns.split(","), page)),
    doUpdateSubscription: (body) => dispatch(updateSubscriptionAsync(body)),
    doRenewSubscription: (body) => dispatch(renewSubscriptionAsync(body)),
    clearSubscriptions: () => dispatch(clearGetSubscriptionCodeListState()),
    clearRenewSubscriptionErrorAll: () => dispatch(clearPatientRegistrationState()),
    initiatePayment: () => dispatch(startPatientRegistrationPayment()),
    cancelPayment: () => dispatch(cancelPatientRegistrationPayment()),
    /** verify with bakend to complete registration after check payment details  */
    verifyPayment: payment => dispatch(registrationPaymentCapture(payment)),
    /** in case of payment failed */
    paymentFailed: err => dispatch((failedPatientRegistrationPayment(err))),
    clearPatientRegistrationState: () => dispatch(patientRegistrationClearState())
    
})

export default connect(mapStateToProps, mapDispatchToProps)(AllSubscriptionCodeComponent)