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

import { Formik, Form } from 'formik'
import QualificationCard from '../../../../sign-up/cards/educator/tabs/qualification/qualification-card.component'
import WithSpinner from '../../../../utility/hoc/spinner/with-spinner.component'
import ToastComponent from '../../../../utility/toast/toast.component'
import { UserProfile_Enum } from "../../../../../redux/helpers/action-enums"
import {validators} from './educator-work-info.validation.rules'
import {initialValues} from './educator-work-info.initial-values'
import {submitWorkInformationAsync, clearAuthenticationState } from '../../../../../redux/user/user.action'
import { getErrorMessage, getUserIsSubmitting } from '../../../../../redux/user/selectors'

import "./work-information-edit.styles.scss"

const WorkInformationEditComponent = ({
    showQualification=true,
    showCertification=true,
    showWorkExperience=true,
    exitingRecords=[],
    isSubmitting, errorMessages,
    doDismissError,doSubmitChanges    
}) => {

    const [ udpateType, setUpdateType ] = useState(-1)
    
    useEffect(() => {
        setUpdateType(
            showQualification ? UserProfile_Enum.WorkExperienceUpdateEnum.QualificationDetails :
            showCertification ? UserProfile_Enum.WorkExperienceUpdateEnum.CertificateDetails :
            UserProfile_Enum.WorkExperienceUpdateEnum.WorkExpDetails
        )        
    },[])

    const SubmitButtonWithSpinner = WithSpinner(
        () =>
          (<button type="submit" name="submit" 
            className="p-2 next btn-register ml-3 mt-3">
             Submit                                   
          </button>)
        
        )

    
    const dismissToast = e => {
        doDismissError()
    }

    return (  
        <>
        <Formik
                initialValues={{
                    ...initialValues(showQualification, showWorkExperience)
                }}
                validationSchema={validators(showQualification, showWorkExperience)}
                onSubmit={ data => {
                    //Expectation is always one key: either of qualification, work experience or certification
                    Object.keys(data).forEach(function(key) {
                        const arr = [ ...data[key], ...exitingRecords]
                        data[key] = arr
                      })

                      const body ={
                        UpdateType: udpateType,
                        UpdateInfo: JSON.stringify(data)
                        }
                    doSubmitChanges(body)

                }}
            >
                {formik => (
                    <Form className="msform">
                        <QualificationCard 
                            showQualification={showQualification}
                            showCertification={showCertification}
                            showWorkExperience={showWorkExperience}
                            />
                        <SubmitButtonWithSpinner defaultHeight={false} isLoading={isSubmitting}/>

                    </Form>
                )}
        </Formik>
        { !!errorMessages ? <ToastComponent message={errorMessages} onclose={dismissToast}/> : null }
        </>
    )
}



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

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

  })

export default connect(mapStateToProps, mapDispatchToProps)( WorkInformationEditComponent)