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

import WorkInformationEditComponent from "./modal-views/work-information-edit/work-information-edit.component"
import GenericModalComponent from '../../utility/hoc/modal-views/generic.modal.component'
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import ToastComponent from '../../utility/toast/toast.component'

import { getProfileDataSaveResult, getErrorMessage, getUserIsSubmitting  } from '../../../redux/user/selectors'
import { clearAuthenticationState, submitWorkInformationAsync } from '../../../redux/user/user.action'

import { MettaSvr_Common } from '../../../redux/helpers/action-enums'
import { UtilityJsonArray } from '../../../redux/helpers/enum-string-array-utility'
import { SpecialCertificationElement, QualificationElement, WorkExperienceElement } from "./modal-views/work-information-edit/work-information-elements"

const WorkInformationComponent = ({userProfile, readOnly=false, 
    profileDataSaveResult, errorMessages,
    doDismissError, doSubmitChanges, isSubmitting
}) => {
    const [showWorkInfoEdit, setShowWorkInfoEdit ] = useState(false)
    const [onlyWorkExperience, setOnlyWorkExperience] = useState(false)
    const [onlyQualification, setOnlyQualification] = useState(false)
    const [onlySpecialCertifcate, setOnlySpecialCertifcate] = useState(false)

    const [qualificationDetails, setQualificationDetails] = useState([])
    const [workExDetails, setWorkExDetails] = useState([])
    const [certificateDetails, setCertificateDetails] = useState([])

    useEffect(() => {
        if (!!userProfile){
            setQualificationDetails( UtilityJsonArray(userProfile.qualifDetails, "Qualification"))
            setWorkExDetails(UtilityJsonArray(userProfile.workExpDetails, "WorkExperience"))
            setCertificateDetails(UtilityJsonArray(userProfile.certDetails, "Certification"))
        }
    },[userProfile])

    useEffect(() => {
        if(!!profileDataSaveResult && true === profileDataSaveResult){
            showModal(false, false, false, false)
            doDismissError()
        }
    },[profileDataSaveResult])

    const PerSectionHeader = ({title, func}) =>(
        <div className="well">
            <div className="width70 text-left">
            <h3 className="no-m">{title}</h3>
            </div>
            <div className="width30 text-right">
                <button type="button" className="btn p-1" disabled={readOnly} onClick = {e => func()}>
                    <i className="icon-plus"></i>                                                    
                </button>   
            </div>
            <div className="clearfix"></div>
        </div>
    )

    const showModal = (state, isWorkEx, isQualification, isSpecialCertificate) => {
        // if work info edit closes reset all states to false
        
        setOnlyWorkExperience(isWorkEx)
        setOnlySpecialCertifcate(isSpecialCertificate)
        setOnlyQualification(isQualification)
        
        setShowWorkInfoEdit(state)        
    }

    const dismissToast = e => {
        doDismissError()
    }

    return ( <>
        

        { !!userProfile && userProfile.userType === MettaSvr_Common.UserTypeEnum.Educator ?
            <>        
                
                <PerSectionHeader title="Highest Qualification" func={() => showModal(true, false, true, false)}/>
                <ul className="list-unstyled user_data text-left row">
                    {/* Education Qualification*/}

                    <QualificationElement items={qualificationDetails} qualificationDetails={qualificationDetails}
                     submitAsync={doSubmitChanges}/>
                    
                    
                </ul>
                <PerSectionHeader title="Special Certifications" func={() => showModal(true, false, false, true)}/>                
                                
                <ul className="list-unstyled user_data text-left row">

                    {/* Special Certification*/}

                    
                    <SpecialCertificationElement items={certificateDetails} certificateDetails={certificateDetails} 
                        submitAsync={doSubmitChanges}/>
                    
                </ul>
                <PerSectionHeader title="Work experience Details" func={() => showModal(true, true, false, false)}/>                
                <ul className="list-unstyled user_data text-left row">

                    {/* Work Experience*/}
                    <WorkExperienceElement items={workExDetails} workExDetails={workExDetails}
                     submitAsync={doSubmitChanges} />
                    
                </ul>
                <div className="clearfix"></div>
            </>
            :
            <span>Not Applicable</span>
        }

        { 
        //Show error messages specific to this page only and not from modal views. e.g. Delete error message
        !!errorMessages && !showWorkInfoEdit ? <ToastComponent message={errorMessages} onclose={dismissToast}/> : null 
        }

        {
            showWorkInfoEdit ?
            <GenericModalComponent
                show={showWorkInfoEdit}
                onHide={() => showModal(false, false, false, false)}
                title={"Change Work Information"}
            >
                <WorkInformationEditComponent
                    showQualification={onlyQualification}
                    showCertification={onlySpecialCertifcate}
                    showWorkExperience={onlyWorkExperience}
                    exitingRecords={
                        onlyWorkExperience ? workExDetails :
                        onlySpecialCertifcate ? certificateDetails :
                        qualificationDetails 
                    }
                />
            </GenericModalComponent>
            : null
        }
        
    </> );
}
 


const mapStateToProps = (state) => ({    
    profileDataSaveResult: getProfileDataSaveResult(state),  
    errorMessages: getErrorMessage(state),
    isSubmitting: getUserIsSubmitting(state)  
})

const mapDispatchToProps = dispatch => ({
    doSubmitChanges: (body) => dispatch(submitWorkInformationAsync(body)),
    doDismissError: () => dispatch(clearAuthenticationState())

  })
export default connect(mapStateToProps, mapDispatchToProps )(WorkInformationComponent)