import * as React from "react";
import * as Yup from "yup";
import { Link, RouteComponentProps } from "react-router-dom";
import { Field, Formik, Form } from "formik";
import { AccountController_RecoverPassword } from "../../../../apiClient/routes";
import http from "../../../../services/httpService";
import { toast } from "react-toastify";

export const PasswordRecovery = (props: RouteComponentProps) => {
	React.useEffect(() => {
		document.title = "Zapomenuté heslo";
	}, []);

	const handleSubmit = (values: {email:string}) => {
		http.post(AccountController_RecoverPassword, values).then((response) => {
			toast.success('👍 Žádost o obnovení hesla odeslána! Zkontrolujte evůj email.', {
				position: "top-right",
				autoClose: 3000,
				hideProgressBar: true,
				closeOnClick: true,
				pauseOnHover: false,
				draggable: true,
				progress: undefined,
			});

			props.history.push("/login");
		}).catch(e => {
			console.log(e);
		});
	}

	const passwordRecoveryValidationSchema = Yup.object().shape({
		email: Yup.string().required("Zadejte emailovou adresu!").email("Nevalidní emailová adresa!")
	});

	return (
		<div className="container">
			<div className="row">
				<div className="col-lg-3"></div>
				<div className="col-lg-6">
					<Formik
						initialValues={{ email: '' }}
						validationSchema={passwordRecoveryValidationSchema}
						onSubmit={(values: {email:string}) => { handleSubmit(values); }}
					>
						{({ errors, handleReset, handleSubmit, touched }) => (
							<Form onReset={handleReset} onSubmit={handleSubmit}>
								<div className="checkout__input">
									<p>Email<span>*</span></p>
									<Field name="email" type="email" placeholder="Emailová adresa"
										className={(touched.email && errors.email)
											? 'input__error'
											: (touched.email && !errors.email ? 'input__success' : '')}
									/>
									{errors && touched.email && errors.email && <><label className="error-message">{errors.email}</label></>}
								</div>
								<button type="submit" className="site-btn">Obnovit heslo</button>
								<div className="d-flex justify-content-center mt-2">
									<p><Link className="login__link" to="/login">{"-> Zpět na přihlášení <-"}</Link></p>
								</div>
							</Form>
						)}
					</Formik>
				</div>
				<div className="col-lg-3"></div>
			</div>
		</div>
	);
}
