import React from 'react'
import { Formik, Form } from 'formik'
import { connect } from 'react-redux'
import AddressCard from '../../../../sign-up/cards/educator/tabs/address-card.component'
import ToastComponent from '../../../../utility/toast/toast.component'
import WithSpinner from '../../../../utility/hoc/spinner/with-spinner.component'
import {submitUserProfileAsync, clearAuthenticationState } from '../../../../../redux/user/user.action'
import { getCurrentUserProfile, getSaveResult, getErrorMessage, getUserIsSubmitting } from '../../../../../redux/user/selectors'

import {AddressInformationValidators } from '../personal-information-edit/personal-information-edit-form-validation'
import { AddressInformationInitialValues } from '../personal-information-edit/personal-information-edit-form-initial-values'
import './address-information-edit.styles.scss'

const AddressInformationEditComponent = ({
    currentUserProfile, errorMessages, isSubmitting,
    doSaveUserProfile, doDismissError
}) => {
    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={{
                    ...AddressInformationInitialValues(currentUserProfile)
                }}
                validationSchema={AddressInformationValidators}
                onSubmit={ values => {
                    doSaveUserProfile(values)                    
                }}
            >
                {formik => (
                    <Form className="msform">
                        <AddressCard />
                        <SubmitButtonWithSpinner defaultHeight={false} isLoading={isSubmitting}/>

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

    </>)
}
 
const mapStateToProps = (state) => ({
    currentUserProfile: getCurrentUserProfile(state),
    saveResult: getSaveResult(state),
    errorMessages: getErrorMessage(state),
    isSubmitting: getUserIsSubmitting(state)
})

const mapDispatchToProps = dispatch => ({
    doSaveUserProfile: (body) => dispatch(submitUserProfileAsync(body)),
    doDismissError: () => dispatch(clearAuthenticationState())
  })

export default connect(mapStateToProps, mapDispatchToProps)(AddressInformationEditComponent)