import React, { useState, useEffect } from "react";
import { Form, Input, Button, Checkbox } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useHistory, Link } from "react-router-dom";
//////////////////////////////////
import jwt_decode from "jwt-decode";
// import store from './vuex/store';
import thunk from "redux-thunk";
import { createStore, combineReducers, applyMiddleware } from "redux";
import { connect } from "react-redux";
/////////////////////////////////

import getGQL from "../utils/getGQL";
import "../styles/RegisterForm.css";
import { doLogin } from "../actions/authActions";

// import { BrowserRouter as Router, Route } from 'react-router-dom';
// import createHistory from 'history/createBrowserHistory';

// const history = createHistory()

//////////////////////////////////////////////////////////////
// const store = createStore(applyMiddleware(thunk)) //вторым параметром идет миддлварь

const LoginForm = ({ store, history, doLogin, isLoggedIn }) => {
  // const history = useHistory();
  const [form] = Form.useForm();
  const [login, setLogin] = useState("");
  const [password, setPassword] = useState("");

  useEffect(() => {
    isLoggedIn && history.push("/private");
  }, [isLoggedIn]);

  const onFinish = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  // let p = getGQL('http://player.asmer.fs.a-level.com.ua/graphql')(
  //   let p = getGQL('/graphql')(
  //     `query Login{
  //     login(login: "${login}", password: "${password}")
  //     }`
  //   ).then((data) =>
  //     console.log(data)
  // )

  // store.dispatch(actionPending())
  // p.then(data => store.dispatch(actionResolved(data)))

  /////////////////////////////////////////////////////////////////////////

  function onLogin() {
    doLogin && doLogin(login, password);
    console.log(login);
  }

  return (
    <div className="registerForm">
      {/* <div className="wrapperRegisterForm"> */}
      <div>
        <Form
          name="basic"
          form={form}
          // initialValues={{
          //   remember: true,
          // }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="Username"
            name="username"
            value={onLogin}
            onChange={(e) => setLogin(e.target.value)}
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input
              prefix={<UserOutlined className="site-form-item-icon" />}
              onChange={(e) => {
                console.log(e.target.value);
                form.setFieldsValue({ username: e.target.value });
              }}
            />
          </Form.Item>

          <Form.Item
            label="Password"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            rules={[
              {
                required: true,
                message: "Please input your password!",
              },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined className="site-form-item-icon" />}
            />
          </Form.Item>
          {/* 
        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>Remember me</Checkbox>
        </Form.Item> */}

          <Form.Item>
            <Button 
            type="primary" 
            htmlType="submit" 
            // disabled = {!onLogin ? true : false}
            onClick={onLogin}
            >
              Submit
            </Button>
            {/* <Button
              onClick={() => {
                history.push("/library");
              }}
            >
              Library
            </Button> */}
            <Link to="/" className="link-approval">Registration</Link>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

const mapStateToProps = (state) => ({
  isLoggedIn: !!state.auth.token,
});

const mapDispatchToProps = (dispatch) => ({
  doLogin: (login, password) => dispatch(doLogin(login, password)),
});

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

// if(type == 'PROMISE') {
//   {
//     status PENDING ||
//           FULFILED ||
//           REJECTED
//   }
// }
// action PENDING = () => (
//   {type: 'promise', status: 'PENDING', payload: 'null', error: 'null'}
// )
// action FULFILED =() => (
//   {type: 'SET_STATUS', status: 'RESOLVED', payload, error: null }
// )
// action REJECTED =() => (
//   {type: 'SET_STATUS', status: 'REJECTED', payload: null, error}
// )
