import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'
import { useParams } from "react-router-dom"
import { Formik, Form } from 'formik'
import { ATextField } from '../../form-fields/form-field.component'
import ToastComponent from "../../utility/toast/toast.component";
import WithSpinner from "../../utility/hoc/spinner/with-spinner.component"
import {getCurrentUser, getGetIsPatient} from '../../../redux/user/selectors'
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component"

import { getIsSaving, getErrorMessage, getSavedResult, getResult, getIsFetching } from '../../../redux/dashboard/diet-plan/selectors'
import { createDietPlanStart, clearDietPlanState, fetchDietPlanListStart } from '../../../redux/dashboard/diet-plan/diet-plan.action'
import { decryptURIparams } from '../../utility/Utils'

import {initialValues} from "./diet-plan.initial-values"
import {validationSchema} from './diet-plan.validation.rules'
import {DietPlanPatientInfoComponent as Patient} from './child-views/patient-info.component'
import {DietPlanBodyComponent as Body} from './child-views/body.component'
import {DietPlanHeaderComponent as Header} from './child-views/header.component'
import './diet-plan.styles.scss'

const DietPlanComponent = ({currentUser, isSaving, errorMessage, isPatient, dietPlanSaved,fetching, fetchedResult, doDismissError, doSaveDietPlan, doFetchDietChart, doClearAll
}) => {
    const [patientDP, setPatientDP] = useState(null)
    const { patientId } = useParams()
    useEffect(() => {
        // only fetch for patients
        if (isPatient){
            doFetchDietChart(currentUser.userId)
        }
        return () => {        
            doClearAll()
        }
    },[])

    useEffect(() => {
        if (!!fetchedResult){
            let diet_plan = JSON.parse(fetchedResult.dietPlan)
            setPatientDP(diet_plan)
            // console.log(diet_plan)
            // console.log(JSON.parse(fetchedResult.dietPlan))
        }
    },[fetchedResult])
    
    
    const LoginButtonWithSpinner = WithSpinner(() =>
        (
          <button type="submit" className="btn-login">Submit</button>
        )
    )

    const dismissToast = theForm => {
        if (!!theForm){
            theForm.resetForm()
        }
        doClearAll()
      }
    

    const displayForm = initial => (
        <Formik
            initialValues={initial}
            validationSchema={validationSchema}
            onSubmit={values => {
            //   console.log(values)
            let body = {
                PatientId: decryptURIparams(patientId),
                DietPlan: JSON.stringify(values)
            }
            doSaveDietPlan(body)
            }}
        >
            {formik => (
                <Form>
            
                    <fieldset disabled={isPatient ? true : false}>     
                        <div className='border-wrapper'>
                            <Header educatorName={currentUser.loginUserName}/>
                        </div>
                        <div className='border-wrapper'>
                            <Patient />
                        </div>                            
                        <div className='border-wrapper'>
                            <Body />
                        </div>
                        
                    </fieldset>
                    {
                        isPatient ? 
                            null :
                            <div className="text-center pt-4">
                                <LoginButtonWithSpinner isLoading={isSaving} defaultHeight={false}/>                                  
                            </div>
                    }
                    { !!errorMessage == false && dietPlanSaved ? 
                        <ToastComponent success={true} message="Diet plan saved successfully" onclose={e => dismissToast(formik)}/> : null }
                </Form>
            )}
        </Formik>
    )


    return(
        <WrapperPanelComponent>

            {
                !isPatient ?            
                    displayForm(initialValues)    
                : 
                isPatient && !!patientDP ?
                    displayForm(patientDP)
                :
                null
            }
            { !!errorMessage ? <ToastComponent message={errorMessage} onclose={dismissToast}/> : null }
                                
        </WrapperPanelComponent>

    )
}

const mapStateToProps = state => ({
    currentUser: getCurrentUser(state),
    errorMessage: getErrorMessage(state),
    isSaving: getIsSaving(state),  
    isPatient: getGetIsPatient(state),
    dietPlanSaved: getSavedResult(state) ?? false,
    fetchedResult: getResult(state),
    fetching: getIsFetching(state)
  })
  
  const mapDispatchToProps = dispatch => ({
    doDismissError: () => dispatch(),
    doFetchDietChart: (patientId) => dispatch(fetchDietPlanListStart(patientId)),
    doSaveDietPlan: (body) => dispatch(createDietPlanStart(body)),
    doClearAll:() => dispatch(clearDietPlanState())
  })
export default connect(mapStateToProps, mapDispatchToProps)( DietPlanComponent)