import React, {useState, useEffect}  from 'react'
import { Formik, Form } from 'formik'
import { connect } from 'react-redux'
import {initialValues} from './add-subscription.initial-values'
import {validators} from './add-subscription-code.validators'
import ToastComponent from '../../utility/toast/toast.component'
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import { ASelect } from '../../../components/form-fields/form-field.component'
import ModalComponent from './modal-view.component'
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component";
import { generateSubscriptionCodeAsync, clearPostSubscriptionGenerateState } from '../../../redux/dashboard/subscription-codes/subscription-codes.action'
import {fetchEducatorListAsync } from '../../../redux/dashboard/educator-list/educator-list.action'
import {getGetIsDoctor, getDoctors, getEducators, getCurrentUser, 
    getSubscriptionCoderFetchInProgress, getSubscriptionCoderFetchingErrorMessages, getSubscriptionCodeResult } from '../../../redux/dashboard/subscription-codes/selectors'

import './add-subscription-code.styles.scss'

const AddSubscriptionCodeComponent = ({doctors, educators, errorMessages, postGenerateSubscriptionCode, isDoctor,
     inProgress, subscriptionCode, theUser, clearState, doFetchEducatorList}) => {

    const [showSubsCodeModal, setShowSubsCodeModal] = useState(false)

    useEffect(() =>{
        setShowSubsCodeModal(!inProgress && !!subscriptionCode)
    },[inProgress, subscriptionCode])
    
    useEffect(() => {
        if(isDoctor)
            doFetchEducatorList()
    }, [])

    const dismissToast = e => {
        clearState()
    }

    const ButtonWithSpinner = WithSpinner(
        () =>
          (
            <div className="col-md-12 text-center m-t-lg">                             
                <button type="submit" className="btn-login">Add</button>
            </div>
        )
    )

    return (   
        <WrapperPanelComponent>
            <div className="subscription-box text-center">
                <Formik
                        initialValues={{
                            ...initialValues
                        }}
                        validationSchema={isDoctor ? validators: null}
                        onSubmit={ values => {
                            postGenerateSubscriptionCode(isDoctor ? values.educatorId: theUser.userId)
                        }}
                    >
                        {formik => (
                            <Form className="msform">

                            <fieldset className="mt-4">
                                <div className="form-row">
                                    <div className="form-group col-md-6">
                                        <ASelect name="doctorId" label="Doctor ID/Name" options={doctors}/>                    
                                    </div>
                                    <div className="form-group col-md-6">
                                        <ASelect name="educatorId" label="Educator ID/Name" options={educators}/>                                                        
                                    </div>
                                </div>
                            </fieldset>                                
                
                            <ButtonWithSpinner defaultHeight={false} isLoading={inProgress}/>
                            {
                                !!subscriptionCode ? (
                                    <ModalComponent
                                        show={showSubsCodeModal}
                                        subscriptionCodeValue={subscriptionCode}
                                        onHide={() => {
                                                setShowSubsCodeModal(false)
                                                clearState()
                                            }
                                        }
                                    >
                                    </ModalComponent>
                                ): null
                            }
                            
                        </Form>                    
                        )
                        }
                    </Formik>
                { !!errorMessages ? <ToastComponent message={errorMessages} onclose={dismissToast}/> : null }
                
            </div>
        </WrapperPanelComponent>
    )
}
 
const mapStateToProps = state => ({
    doctors: getDoctors(state),
    educators:  getEducators(state),
    theUser: getCurrentUser(state),
    isDoctor: getGetIsDoctor(state),
    inProgress: getSubscriptionCoderFetchInProgress(state),
    errorMessages: getSubscriptionCoderFetchingErrorMessages(state),
    subscriptionCode: getSubscriptionCodeResult(state),
    
})

const mapDispatchToProps = dispatch => ({
    postGenerateSubscriptionCode: (theEducatorId) => dispatch(generateSubscriptionCodeAsync({educatorId: theEducatorId})),
    clearState: () => dispatch(clearPostSubscriptionGenerateState()),
    doFetchEducatorList: (page=1,activeStatus=true) => dispatch(fetchEducatorListAsync(page,{isActive:activeStatus}))
  })

export default connect(mapStateToProps, mapDispatchToProps)(AddSubscriptionCodeComponent)