import { connect } from "react-redux";
import { login, getUser, refreshToken } from "@/actions/auth";
import axiosAPI from "@/config/axios";
import { getPT } from "@/actions/PT";

import React, { Component } from "react";
import BasePage from "@/components/Layout/BasePage";
import { Row, Col, Input, Card, CardHeader, CardBody, Button, CardFooter, CustomInput } from "reactstrap";
import Router from "next/router";
import FormValidator from "@/components/Forms/Validator.js";

class Login extends Component {
	constructor(props) {
		super(props);
	}
	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) => {
		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);
			console.log(auth);
			if (auth.success) {
				axiosAPI.defaults.headers.Authorization = `Bearer ${auth.access_token}`;
				const dataUser = await getUser();
				console.log(dataUser);
				this.props.setUser(dataUser.data);
				if (dataUser.data.peran[0].peran.id === 2022) {
					const org_id = dataUser.data.peran[0].organisasi.id;
					const pt = await getPT({ id: org_id });
					if (pt?.success) {
						this.props.setPT(pt.data);
					}
					Router.push({ pathname: "/app/pt/pemantauan" });
				} else {
					Router.push({ pathname: "/app/pemantauan" });
				}
			} else {
				this.setState({ error: auth.message || auth.error });
			}
		}
		// e.preventDefault();
	};

	/* 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 (
			<div className="block-center mt-4 wd-xl">
				<Card className="card card-flat">
					<img className="card-img-top" src="/static/img/logo.png" alt="Logo" />
					<CardBody className="card-body">
						{" "}
						<h5 className="card-title text-center py-2 bg-gray">Aplikasi Perguruan Tinggi Bermasalah </h5>
						{this.state.error}
						<form onSubmit={this.onSubmit} method="post" name="formLogin">
							<div className="form-group">
								<label className="col-form-label">Username *</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 *</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>
							<Button color="primary" type="submit" block className=" mt-3">
								Login
							</Button>
						</form>
					</CardBody>
				</Card>
			</div>
		);
	}
}
Login.Layout = BasePage;
const mapStateToProps = (state) => ({ user: state.user });
const mapDispatchToProps = (dispatch) => ({
	setUser: (payload) => dispatch({ type: "SET_USER", payload }),
	setPT: (payload) => dispatch({ type: "SET_PT", payload }),
});

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