// import React, { Component,useState } from 'react';
import React, { Component} from 'react';
import BasePage from '@/components/Layout/BasePage';
import Link from 'next/link';
import { Input, CustomInput } from 'reactstrap';
import * as actions from '../store/actions/actions';

import FormValidator from '@/components/Forms/Validator.js';
import { dispatch } from 'd3';
import Router, { withRouter } from 'next/router'

// import useUser from '../lib/useUser';
// import fetchJson from '../lib/fetchJson';

const year = new Date().getFullYear()


class Login extends Component {

    // mutateUser = useUser({
    //     redirectTo: '/profile-sg',
    //     redirectIfFound: true,
    // })

    // [errorMsg, setErrorMsg] = useState('')


    state = {
        formLogin: {
            uname: '',
            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(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) {
            //this.props.logged('signin')
            //Router.push('/singleview');

            // const body = {
            //     username: this.state.formLogin.uname,
            //     password: this.state.formLogin.password
            //   }

            // try {
            //     mutateUser(
            //         await fetchJson('/api/login', {
            //         method: 'POST',
            //         headers: { 'Content-Type': 'application/json' },
            //         body: JSON.stringify(body),
            //         })
            //     )


            // } catch (error) {
            // console.error('An unexpected error happened:', error)
            // setErrorMsg(error.data.message)
            // }
            
            //main route
            Router.push('/app/projects');
        };

    }

    /* 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">
                <div className="card card-flat">
                    {/* <div className="card-header text-center bg-white">
                        <a href="">
                            <img className="block-center " src="/static/img/logo.png" alt="Logo"/>
                        </a>
                    </div> */}
                    <img class="card-img-top" src="/static/img/logo.png" alt="Logo"></img>
                    <div className="card-body">
                        <h5 class="card-title text-center py-2 bg-gray">Aplikasi Perguruan Tinggi Bermasalah </h5>
                        {/* <p className="text-center py-2">Aplikasi Perguruan Tinggi Bermasalah </p> */}
                        <form className="mb-3" name="formLogin" onSubmit={this.onSubmit}>
                            <div className="form-group">
                                <div className="input-group with-focus">
                                    {/* <Input type="email"
                                        name="email"
                                        className="border-right-0"
                                        placeholder="Enter username"
                                        invalid={this.hasError('formLogin','email','required')||this.hasError('formLogin','email','email')}
                                        onChange={this.validateOnChange}
                                        data-validate='["required", "email"]'
                                        value={this.state.formLogin.email}/> */}

                                    <Input placeholder="Enter User Name"
                                    name="uname"
                                    className="border-right-0"
                                    invalid={this.hasError('formLogin','uname','required')}
                                    onChange={this.validateOnChange}
                                    data-validate='["required"]'
                                    value={this.state.formLogin.uname}
                                     />
                                    <div className="input-group-append">
                                        <span className="input-group-text text-muted bg-transparent border-left-0">
                                            <em className="fa fa-user"></em>
                                        </span>
                                    </div>
                                    { this.hasError('formLogin','uname','required') && <span className="invalid-feedback">Field is required</span> }
                                    {/* { this.hasError('formLogin','email','email') && <span className="invalid-feedback">Field must be valid email</span> } */}
                                </div>
                            </div>
                            <div className="form-group">
                                <div className="input-group with-focus">
                                    <Input type="password"
                                        id="id-password"
                                        name="password"
                                        className="border-right-0"
                                        placeholder="Password"
                                        invalid={this.hasError('formLogin','password','required')}
                                        onChange={this.validateOnChange}
                                        data-validate='["required"]'
                                        value={this.state.formLogin.password}
                                    />
                                    <div className="input-group-append">
                                        <span className="input-group-text text-muted bg-transparent border-left-0">
                                            <em className="fa fa-lock"></em>
                                        </span>
                                    </div>
                                    <span className="invalid-feedback">Field is required</span>
                                </div>
                            </div>
                            {/* <div className="clearfix">
                                <CustomInput type="checkbox" id="rememberme"
                                    className="float-left mt-0"
                                    name="remember"
                                    label="Remember Me">
                                </CustomInput>
                                <div className="float-right">
                                    <Link href="/pages/recover" as="/recover"><a className="text-muted"> </a></Link>
                                </div>
                            </div> */}
                            <button className="btn btn-block btn-primary mt-3" type="submit">Login</button>
                        </form>
                    </div>
                </div>
                <div className="p-3 text-center">
                    {/* <span className="mr-2">&copy;</span> */}
                    <span>&copy; {year} - Dikti</span>
                    {/* <span className="mx-2">-</span>
                    <span>Dikti</span> */}
                    <br/>
                    <span> </span>
                </div>
            </div>
        );
    }
}

Login.Layout = BasePage;

export default Login;
