import React, { useEffect } from 'react'
import PropTypes from 'prop-types'
import { Formik, Form } from 'formik'
import { Persist } from 'formik-persist'
import * as Yup from 'yup'
import FormikControl from '../FormikControls'
import ButtonPrimary from '../controls/ButtonPrimary'
import ButtonSecondary from '../controls/ButtonSecondary'
import { FormLogin } from './FormLogin'
import { SubmitFormResult } from '../../SubmitFormResult';

export const FormPasswordRecovery = (props) => {
    const { setPopupTitle, setPopupContent, setPopupOpened, close } = props

    useEffect(() => {
        if (setPopupTitle) { setPopupTitle('Forgotten password recovery') }
    })

    const initialValues = {
        email: '',
    }

    const validationSchema = Yup.object({
        email: Yup.string()
            .required('Required')
            .email('Must be a valid email address'),
    })

    const onSubmit = values => {
        setPopupOpened(false)
        setTimeout(() => {
            setPopupContent(<SubmitFormResult setPopupTitle={setPopupTitle} data={values} />)
            setPopupOpened(true)
        }, 200);
    }

    const goLogin = () => {
        setPopupOpened(false)
        setTimeout(() => {
            setPopupContent(<FormLogin setPopupTitle={setPopupTitle} setPopupContent={setPopupContent} setPopupOpened={setPopupOpened} close={close} />)
            setPopupOpened(true)
        }, 200);
    }

    return (
        <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={onSubmit}
        >
            {formik => {
                return (
                    <div className="overflow-y-auto max-h-screen-80">
                        <Form>
                            <div className="p-3">
                                <FormikControl
                                    control='string'
                                    name='email'
                                    label='Email'
                                    placeholder='Enter email'
                                />
                            </div>
                            <div className="px-2 pt-4 pb-1 mb-0 bg-primary-200 border-t sm:rounded-b-lg">
                                <ButtonPrimary type="submit" text="Recover" disabled={!formik.isValid || !formik.dirty} />
                                <div className="my-3">
                                    <ButtonSecondary type="button" text="Go to Sign In" action={goLogin} />
                                </div>
                            </div>
                            <Persist name="password-recovery-form" isSessionStorage />
                        </Form>
                    </div>
                )
            }}
        </Formik>
    )
}

FormPasswordRecovery.propTypes = {
    setPopupTitle: PropTypes.func,
    setPopupContent: PropTypes.func,
    setPopupOpened: PropTypes.func,
    close: PropTypes.func,
}