import React, {useState, useEffect} from 'react'
import { Formik, Form } from 'formik'
import { connect } from 'react-redux'
import moment from 'moment'

import { CSSTransition, TransitionGroup } from 'react-transition-group'
import { registerEducatorAsync, clearEducatorRegistrationState,
     setEducatorRegistrationCurrentPage, postEducatorFailure } from '../../../../redux/educator/educator.action'

import { validators } from "./educator-register.validation.rules"

import PersonalCard from './tabs/personal-card.component'
import QualificationCard from './tabs/qualification/qualification-card.component'
import ConfirmSubmitCard from '../common-cards/final-card.component'
import AddressCard from './tabs/address-card.component'
import {initialValues} from './educator-register.initial-values'
import ToastComponent from '../../../utility/toast/toast.component'
import WithSpinner from '../../../utility/hoc/spinner/with-spinner.component'
import { TermsAndConditionContentComponent, TermsAndConditionComponent } from '../../../utility/terms_and_conditions/terms_and_conditions.component'
import {getTermsAndConditionsContent} from '../../../../redux/user/selectors'
import {fetchUserTermsAndConditionsAsync} from '../../../../redux/user/user.action'

import './educator-register.styles.scss'

const EducatorRegisterCard = props => {

    // terms and condition setup
    const [showTerms, setShowTerms ] = useState(false)
    const [acceptTerms, setAcceptTerms ] = useState(false)
    // terms and condition setup end

    const totalPages = 4
    const {t_n_c_content, errorMessages, inProgress, currentPage ,
        doFetchTermsCondition, validationErrorOccurred, doDismissError } = props

    useEffect(() =>{
        doFetchTermsCondition()
    },[])
    const  doPrevious = (e) => {
        props.doChangeCurrentPageTo(currentPage - 1)        
    }
    
    
    const doNext = () => {        
        if (currentPage < totalPages - 2){    
            props.doChangeCurrentPageTo(currentPage + 1)
        }
    }


    const currentCard = (index) => {
        var displayCard = null
        switch (index) {
            case 0:
                displayCard = <PersonalCard />
                break;

            case 1:
                displayCard = <AddressCard />
                break;
                
            case 2:
                displayCard = <QualificationCard />
                break;

            default:
                displayCard = <ConfirmSubmitCard />
                break;
        }

        return { displayCard, _key: index }
    }

    const dismissToast = e => {
        doDismissError()
    }

    const { displayCard, _key } = currentCard(currentPage)

    const takeOnSubmit = async (formik) => {
        const {values} = formik
        // const {errors} = values
        try {
            //this sequence means submission try, if fails highlight error fields 
            // and then show the alert for error message.
            //e.g. especially useful if last page is filled all okay, but previous pages have error. So in order to 
            //show the message reason and also pin point the errored fields.
            await formik.submitForm()
            await validators.validate(values)
            
        } catch (ex) {
            // console.log('validation error = ', ex.message)
            validationErrorOccurred(ex.message)            
        }
    }

    const SubmitButtonWithSpinner = WithSpinner(
        ({onClickHandler}) =>
          (<button type="button" name="submit" onClick={onClickHandler}
            hidden={currentPage !== totalPages - 2} className="p-2 next btn-register ml-3 mt-3">
             Submit                                   
          </button>)
        
        )
    
// terms and condition setup
    const termsLinkClicked = () => {
        setShowTerms(!showTerms)
    }

    const onTermsModalHide = (accepted) => {
        setAcceptTerms(accepted)
        setShowTerms(false)
    }
// terms and condition setup end    

    return (
        <div id="edu" className="tab-pane">  
            <TermsAndConditionContentComponent content={t_n_c_content} show={showTerms} onHide={onTermsModalHide}/>
          
            <Formik
                initialValues={{
                    ...initialValues
                }}
                validationSchema={validators}
                onSubmit={ values => {
                    // convert to proper format before send
                    // console.log(values)
                    props.doRegister(values)                    
                }}
            >
                {formik => (
                    <Form className="msform">
                        <div className="container">
                            <div className="row" id="progressedu">
                                <div className="active col" id="eduaccount">Personal</div>
                                <div className={currentPage >= 1 ? "col active": "col"} id="eduaddress">Address</div>
                                <div className={currentPage >= 2 ? "col active": "col"} id="edupersonal">Qualification</div>                                
                            </div>
                        </div>
                        <TransitionGroup>
                            <CSSTransition
                                key={_key}
                                timeout={600}
                                classNames="fade"
                            >
                                {
                                    displayCard
                                }
                            </CSSTransition>
                        </TransitionGroup>


                        <div className="d-flex flex-row-reverse">
                            <SubmitButtonWithSpinner defaultHeight={false} isLoading={inProgress} onClickHandler={() => takeOnSubmit(formik)}/>
                            {
                                acceptTerms ? 
                                    <button type="button" name="next" onClick={doNext}
                                        hidden={currentPage >= totalPages - 2} className="p-2 next btn-register ml-3 mt-3">
                                        Next Step                             
                                        </button>:

                                <button type="button" name="next" 
                                    hidden={currentPage >= totalPages - 2} className="p-2 next ml-3 mt-3">
                                    Next Step                             
                                    </button>
                            }
                            <button type="button" name="previous" onClick={doPrevious}
                                hidden={currentPage === totalPages - 1 || currentPage === 0} className="p-2 previous btn-outlines mt-3">Previous</button>
                        </div>
                        <div className={ currentPage > 0 || currentPage == 0 && acceptTerms ? 'hidden': ""}>
                            <TermsAndConditionComponent onLinkClick={termsLinkClicked}/>
                        </div> 
                    </Form>                    
                )
                }
            </Formik>
            { !!errorMessages ? <ToastComponent message={errorMessages} onclose={dismissToast}/> : null }
        </div>

    )
}

const mapStateToProps = (state) => {
    const { educatorRegistration } = state
    return {
        result: educatorRegistration.result,
        orderDetails: educatorRegistration.orderDetails,
        errorMessages: educatorRegistration.errorMessages,
        inProgress: educatorRegistration.inProgress,
        currentPage: educatorRegistration.currentPage,
        t_n_c_content: getTermsAndConditionsContent(state)
    }
}
  
  const mapDispatchToProps = dispatch => ({
    // setCurrentUser: user => dispatch(setCurrentUser(user))
    doRegister: body => {
        const renewedBody = {
            ...body,
            QualifDetails: JSON.stringify({Qualification: body.Qualification}),
            CertDetails: JSON.stringify({Certification: body.Certification}),
            WorkExpDetails: JSON.stringify({WorkExperience: body.WorkExperience}),
        }
        delete renewedBody.Qualification
        delete renewedBody.Certification
        delete renewedBody.WorkExperience
        
        dispatch(registerEducatorAsync(renewedBody))
    },
    doFetchTermsCondition: () => dispatch(fetchUserTermsAndConditionsAsync()),
    doDismissError: () => {
        dispatch(clearEducatorRegistrationState())
    },
    doChangeCurrentPageTo: (pageNum) => {
        dispatch(setEducatorRegistrationCurrentPage(pageNum))
    },
    validationErrorOccurred: (err) => dispatch(postEducatorFailure({message: err}))
  })

export default connect(mapStateToProps, mapDispatchToProps)(EducatorRegisterCard)