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

type SignupProps = RouteComponentProps;

class Signup extends React.Component<SignupProps> {
	state = {
		displayErrorMessage: false
	}

	componentDidMount() {
		document.title = "Registrace";
	}

	handleSubmit = (values: IRegisterIM) => {
		http.post(AccountController_RegisterUser, values, { validateStatus: status => { return status <= 400 } }).then((response) => {
			if (response.status == 200) {
				toast.success('👍 Registrace proběhla úspěšně!', {
					position: "top-right",
					autoClose: 3000,
					hideProgressBar: true,
					closeOnClick: true,
					pauseOnHover: false,
					draggable: true,
					progress: undefined,
				});

				this.props.history.push("/login");
			} else if (response.status == 400) {
				toast.error('Něco se nepovedlo :(', {
					position: "top-right",
					autoClose: 3000,
					hideProgressBar: true,
					closeOnClick: true,
					pauseOnHover: false,
					draggable: true,
					progress: undefined,
				});

				this.setState({ displayErrorMessage: true });
			}
		}).catch(e => {
			console.log(e);
			this.setState({ ...this.state });
		});
	}

	render() {
		const signupValidationSchema = Yup.object().shape({
			email: Yup.string().required("Email je vyžadován!").email("Nevalidní emailová adresa!"),
			password: Yup.string().required("Heslo je vyžadováno!").min(8, "Minimální délka hesla je 8 znaků!"),
			confirmPassword: Yup.string().required("Potvrzení hesla je vyžadováno!").oneOf([Yup.ref('password'), null], "Hesla musí být stejná!")
		});

		const signupInitValues: IRegisterIM = {
			email: '',
			password: '',
			confirmPassword: ''
		}

		return (
			<div className="container">
				<div className="row">
					<div className="col-lg-3"></div>
					<div className="col-lg-6">
						<Formik
							initialValues={signupInitValues}
							validationSchema={signupValidationSchema}
							onSubmit={(values: IRegisterIM) => { this.handleSubmit(values); }}
						>
							{({ errors, handleReset, handleSubmit, touched }) => (
								<Form onReset={handleReset} onSubmit={handleSubmit}>
									<div className="checkout__input">
										<p>Email<span>*</span></p>
										{this.state.displayErrorMessage
											? <label className="error-message">Zadaná emailová adresa je již registrována!</label>
											: ''}
										<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>
									<div className="checkout__input">
										<p>Heslo<span>*</span></p>
										<Field name="password" type="password" placeholder="Heslo"
											className={(touched.password && errors.password)
												? 'input__error'
												: (touched.password && !errors.password ? 'input__success' : '')}
										/>
										{errors && touched.password && errors.password && <><label className="error-message">{errors.password}</label></>}
									</div>
									<div className="checkout__input">
										<p>Potvrzení hesla<span>*</span></p>
										<Field name="confirmPassword" type="password" placeholder="Potvrzení hesla"
											className={(touched.confirmPassword && errors.confirmPassword)
												? 'input__error'
												: (touched.confirmPassword && !errors.confirmPassword ? 'input__success' : '')}
										/>
										{errors && touched.confirmPassword && errors.confirmPassword && <><label className="error-message">{errors.confirmPassword}</label></>}
									</div>
									<button type="submit" className="site-btn">Registrovat se</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>
		);
	}
}

export default Signup;