import * as React from "react";
import * as Yup from "yup";
import { Link, RouteComponentProps } from "react-router-dom";
import { Field, Formik, Form } from "formik";
import { ILoginIM } from "../../../../apiModels/ViewModels";
import { AccountController_AuthenticateUser } from "../../../../apiClient/routes";
import http from "../../../../services/httpService";
import { SetAuthorizationTokenLocalStorage } from "../../../../services/localStorageService";

type LoingProps = {
	displayErrorMessage: boolean,
	onSubmitClick(values: ILoginIM): void
}

class Login extends React.Component<LoingProps> {
	componentDidMount() {
		document.title = "Přihlášení";
	}

	handleSubmit = (values: ILoginIM) => {
		http.post(AccountController_AuthenticateUser, values, { validateStatus: status => { return status <= 400 } }).then((response) => {
			if (response.status == 200) {
				SetAuthorizationTokenLocalStorage(response.data);
				//this.props.history.push("/");
			} else if (response.status == 400) {
				this.setState({ displayErrorMessage: true });
			}
		}).catch(e => {
			console.log(e);
			this.setState({ ...this.state });
		});
	}

	render() {
		const loginValidationSchema = 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(5, "Minimální délka hesla je 5 znaků!")
		});

		const loginInitValues: ILoginIM = {
			email: '',
			password: ''
		}

		return (
			<div className="container">
				<div className="row">
					<div className="col-lg-3"></div>
					<div className="col-lg-6">
						<Formik
							initialValues={ loginInitValues }
							validationSchema={loginValidationSchema}
							onSubmit={(values: ILoginIM, { resetForm }) => {
								this.props.onSubmitClick(values);
								resetForm({ values: { ...loginInitValues, email: values.email } });
							}}
						>
							{({ errors, handleReset, handleSubmit, touched }) => (
								<Form onReset={handleReset} onSubmit={handleSubmit}>
									<div className="checkout__input">
										<p>Email<span>*</span></p>
										{this.props.displayErrorMessage
											? <label className="error-message">Nesprávný email nebo heslo!</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' : '')}
										/>
										<small className="form-text text-muted"><Link className="login__link float-right" to="/passwordRecovery">Zapoměli jste heslo?</Link></small>
										{errors && touched.password && errors.password && <><label className="error-message">{errors.password}</label></>}
									</div>
									<button type="submit" className="site-btn">Přihlásit se</button>
									<div className="d-flex justify-content-center mt-2">
										<p><Link className="login__link" to="/signup">{"-> Vytvořit účet <-"}</Link></p>
									</div>
								</Form>
							)}
						</Formik>
					</div>
					<div className="col-lg-3"></div>
				</div>
			</div>
		);
	}
}

export default Login;