import React, { useEffect, useState } from 'react'
import { Formik, Form } from 'formik'
import { connect } from 'react-redux';
import WrapperPanelComponent from "../../utility/hoc/wrapper-panel/wrapper-panel.component"
import WithSpinner from '../../utility/hoc/spinner/with-spinner.component'
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { formInitialValues } from './user-feedback.initializers'
import {validators } from './user-feedback.validation'
import ToastComponent from '../../utility/toast/toast.component'

import { submitUserFeedbackAsync, clearAuthenticationState } from '../../../redux/user/user.action'
import { getUserIsSubmitting, getErrorMessage,getSaveResult, getFeedbackSubmittedStatus} from '../../../redux/user/selectors'

import "./user-feedback.styles.scss"

const UserFeedBackComponent = ({
    submitting, errorMessage,feedbackSubmissionStatus,
    doClearErrors, doSubmit
}) => {

    useEffect(() =>{
        return () =>{
            doClearErrors()
        }
    },[])
    
    const [stars, setStars] = useState(Array(5).fill(false))

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

    const doChecked = (e, formik) => {
        const index = e.target.value
        const existingStars = stars.map(()=>false)
        
        for (let i = 0; i < index; i++){
            existingStars[i] = true
        }
        setStars(existingStars)
        formik.handleChange(e)
    }
    return (  
        <WrapperPanelComponent>
            <div className="body">
                <div className="containers">
                    <div className={`post ${!feedbackSubmissionStatus ? 'hide':''}`}>
                        <div className="text">Thanks for rating us!</div>
                    </div>
                    <Formik
                            initialValues={formInitialValues}
                            validationSchema={validators}
                            onSubmit={ values => {
                                console.log(values)
                                doSubmit(values)
                            }}
                        >
                            {formik => (
                                <Form className="msform">
                                    
                                    <div className={`star-widget ${feedbackSubmissionStatus ? 'hide':''}`}>
                                        <div className='row'>
                                        { stars.map( (_, index) => {
                                                const identifier = `rate-${index+1}`
                                                return (
                                                    <React.Fragment key={`star-${index}`}>
                                                        <input type="radio" name="StarCount" id={identifier} value={index+1} 
                                                            onChange={e => doChecked(e, formik)}/>
                                                        <label htmlFor={identifier} className={`${stars[index] ? 'checked' : 'unchecked'}`}>
                                                            <FontAwesomeIcon icon="star"/>                                        
                                                        </label>
                                                    </React.Fragment>
                                                    )
                                                }
                                            )
                                        }
                                        </div>
                                        <header></header>
                                        {formik.errors.StarCount ? <div className="validation-error">{formik.errors.StarCount}</div> : null}

                                        <div className="textarea">
                                            <textarea cols="30" rows="10"                                        
                                            name="UserComments" placeholder="Describe your experience.." onChange={formik.handleChange}></textarea>
                                        </div>

                                        {formik.errors.UserComments ? <div className="validation-error">{formik.errors.UserComments}</div> : null}
                                        
                                        <SubmitButtonWithSpinner isLoading={submitting} defaultHeight={false}/>                                  
                                    </div>                      

                                    { !!errorMessage ? 
                                    <ToastComponent message={errorMessage} onclose={doClearErrors}/> : null 
                                    }
                                    
                                    { 
                                    // feedbackSubmissionStatus ? 
                                    //     <ToastComponent success={true} message="Feedback submitted successfully" onclose={e => resetForm(formik)}/> : null 
                                    }
                                </Form>                    
                                )
                                
                            }
                    </Formik>


                </div>                          
            </div>
        </WrapperPanelComponent>
    )
}

const mapStateToProps = (state) => ({
    submitting: getUserIsSubmitting(state),
    errorMessage: getErrorMessage(state),
    feedbackSubmissionStatus: getFeedbackSubmittedStatus(state)
})

const mapDispatchToProps = dispatch => ({
    doSubmit: (body) => dispatch(submitUserFeedbackAsync(body)),
    doClearErrors: () => dispatch(clearAuthenticationState()),
})

export default connect(mapStateToProps, mapDispatchToProps)(UserFeedBackComponent)
    

