import React, { Component } from "react";
import { Input, Card, CardBody, Button } from "reactstrap";
import Router from "next/router";
import FormValidator from "@/components/Forms/Validator.js";
import { connect } from "react-redux";
import { login, getUser } from "@/actions/auth";
import axiosAPI from "@/config/axios";
import { getPT } from "@/actions/PT";

class Login extends Component {
	constructor(props) {
		super(props);
		this.state = {
			/* Group each form state in an object.
		   Property name MUST match the form name */
			error: null,
			formLogin: {
				username: "",
				password: "",
			},
		};
	}

	/**
	 * Validate input using onChange event
	 * @param  {String} formName The name of the form in the state object
	 * @return {Function} a function used for the event
	 */
	validateOnChange = (event) => {
		const input = event.target;
		const form = input.form;
		const value = input.type === "checkbox" ? input.checked : input.value;

		const result = FormValidator.validate(input);

		this.setState({
			[form.name]: {
				...this.state[form.name],
				[input.name]: value,
				errors: {
					...this.state[form.name].errors,
					[input.name]: result,
				},
			},
		});
	};

	onSubmit = async (e) => {
		try {
			const form = e.target;
			const inputs = [...form.elements].filter((i) => ["INPUT", "SELECT"].includes(i.nodeName));

			const { errors, hasError } = FormValidator.bulkValidate(inputs);

			this.setState({
				[form.name]: {
					...this.state[form.name],
					errors,
				},
			});

			console.log(hasError ? "Form has errors. Check!" : "Form Submitted!");
			e.preventDefault();
			if (!hasError) {
				const { username, password } = this.state.formLogin;
				const auth = await login(username, password);
				this.props.setToken(auth.data.token);
				this.props.setUser(auth.data.user);
				axiosAPI.defaults.headers.common["Authorization"] = auth.data.token;
				if (auth.data.user.role.id === 2022) {
					Router.push({ pathname: "/pt/pemantauan" });
				} else if ([2020, 2021].includes(auth.data.user.role.id)) {
					Router.push({ pathname: "/app/pemantauan" });
				} else {
					this.setState({ error: "Akun tidak ada" });
				}
			}
		} catch (error) {
			this.setState({ error: error.response.data.message || error.response });
		}
	};

	/* Simplify error check */
	hasError = (formName, inputName, method) => {
		return this.state[formName] && this.state[formName].errors && this.state[formName].errors[inputName] && this.state[formName].errors[inputName][method];
	};

	render() {
		return (
			<Card className="card card-flat">
				<img className="img-login-1" src="/static/img/logo-login.png" alt="Logo" />
				<CardBody className="card-body">
					{" "}
					<h5 className="card-title text-left py-2 bg-gray border-radius-login">
						<img className="icon-triangle" src="/static/img/icon-caution.png"></img>
						<b>Login Menggunakan Akun PDDIKTI </b>
					</h5>
					{this.state.error}
					<form onSubmit={this.onSubmit} method="post" name="formLogin">
						<div className="form-group">
							<label className="col-form-label">
								Username <span className="star-color">*</span>
							</label>
							<Input type="text" name="username" invalid={this.hasError("formLogin", "username", "required")} onChange={this.validateOnChange} data-validate='["required"]' value={this.state.formLogin.username} />
							{this.hasError("formLogin", "username", "required") && <span className="invalid-feedback">Field is required</span>}
						</div>
						<div className="form-group">
							<label className="col-form-label">
								Password <span className="star-color">*</span>
							</label>
							<Input
								type="password"
								id="id-password"
								name="password"
								invalid={this.hasError("formLogin", "password", "required")}
								onChange={this.validateOnChange}
								data-validate='["required"]'
								value={this.state.formLogin.password}
							/>
							<span className="invalid-feedback">Field is required</span>
						</div>
						{/* <div className="required">* Required fields</div>
						<span>Login Menggunakan Akun PDDIKTI</span> */}
						<div className="btn-radius">
							<Button color="info" type="submit" block className=" mt-3 btn-login">
								<text className="text-login">
									<b>Login</b>
								</text>
							</Button>
						</div>
					</form>
				</CardBody>
			</Card>
		);
	}
}

const mapStateToProps = (state) => ({ user: state.user });
const mapDispatchToProps = (dispatch) => ({
	setUser: (payload) => dispatch({ type: "SET_USER", payload }),
	setToken: (payload) => dispatch({ type: "SET_TOKEN", payload }),
	setPT: (payload) => dispatch({ type: "SET_PT", payload }),
});

export default connect(mapStateToProps, mapDispatchToProps)(Login);
