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

class AccountInfo extends React.Component<RouteComponentProps> {
	state = {
		userDetails: {
			firstName: '',
			lastName: ''
		} as IAccountInfo
	}

	async componentDidMount() {
		document.title = "Účet";
		const user = GetObject();

		if (user !== null) {
			await http.get<IAccountInfo>(AccountController_GetUserDetails).then(async response => {
				const userDetails = await response.data;
				if (userDetails !== null) {
					this.setState({ userDetails });
				}
			});
		} else {
			this.props.history.push("/login");
		}
	}

	async handleSubmit(data: IAccountInfo): Promise<void> {
		await http.post(AccountController_UpdateUserDetails, data, { validateStatus: (status: number) => { return status <= 400 } }).then(async (response) => {
			if (response.status == 200) {
				toast.success("Změny uloženy!", {
					position: "top-right",
					autoClose: 3000,
					hideProgressBar: true,
					closeOnClick: true,
					pauseOnHover: false,
					draggable: true,
					progress: undefined,
				});
			} else if (response.status == 400) {
				toast.error("Chyba!", {
					position: "top-right",
					autoClose: 3000,
					hideProgressBar: true,
					closeOnClick: true,
					pauseOnHover: false,
					draggable: true,
					progress: undefined,
				});
			}
		}).catch(e => {
			console.log(e);
			this.setState({ ...this.state });
		});
	}

	render() {
		const { userDetails } = this.state;

		const accountInfoInitValidationSchema = Yup.object().shape({
			firstName: Yup.string().optional(),
			lastName: Yup.string().optional()
		});

		return (
			<React.Fragment>
				<div className="row">
					<div className="col-lg-3"></div>
					<div className="col-lg-6">
						<Formik
							initialValues={userDetails}
							validationSchema={accountInfoInitValidationSchema}
							enableReinitialize={true}
							onSubmit={(values: IAccountInfo) => (this.handleSubmit(values))}
						>
							{({ errors, handleSubmit, touched }) => (
								<Form onSubmit={handleSubmit}>
									<div className="checkout__input">
										<p>Jméno</p>
										<Field name="firstName" type="text" placeholder="Jméno" />
										{errors && touched.firstName && errors.firstName && <><label className="error-message">{errors.firstName}</label></>}
									</div>
									<div className="checkout__input">
										<p>Příjmení</p>
										<Field name="lastName" type="text" placeholder="Příjmení" />
										{errors && touched.lastName && errors.lastName && <><label className="error-message">{errors.lastName}</label></>}
									</div>
									<button type="submit" className="site-btn">Uložit</button>
								</Form>
							)}
						</Formik>
					</div>
					<div className="col-lg-3"></div>
				</div>
			</React.Fragment>
		);
	}
}

export default AccountInfo;