// eslint-disable-next-line
const preact = require('preact');
const { Component } = require('preact')
const { connect } = require('preact-redux');
const linkState = require('linkstate').default;

const { postData, errorToast } = require('../utils');

const addState = connect(
    (state) => {
        const {
            ws
        } = state;
        function submitLogin(name, password) {
            postData('/account/login', { name, password })
                .then(res => res.json())
                .then(data => {
                    if (data.error) return errorToast(data.error);
                    console.log(data.message);
                    ws.connect();
                })
                .catch(error => errorToast(error));
        }

        return {
            submitLogin,
        }
    },
);


function Login(args) {
    const {
        submitLogin,
    } = args;

    const { password, name } = this.state;

    const loginSubmit = (event) => {
        event.preventDefault();
        submitLogin(name, password);
        this.setState({ name: '', password: '' });
    };

    const loginDisabled = () => {
        return !(password && name);
    };

    return (
        <div class="login">
            <label for="username">Username</label>
            <input
                class="login-input"
                type="email"
                placeholder="username"
                tabIndex={1}
                value={name}
                onInput={linkState(this, 'name')}
            />
            <label for="password">Password</label>
            <input
                class="login-input"
                type="password"
                placeholder="password"
                tabIndex={2}
                value={password}
                onInput={linkState(this, 'password')}
            />
            <button
                class="login-btn"
                tabIndex={4}
                disabled={loginDisabled()}
                onClick={loginSubmit}>
                Login
            </button>
        </div>
    );
}

module.exports = addState(Login);
