// 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, infoToast } = require('../utils');

const addState = connect(
    (state) => {
        const {
            ws
        } = state;

        function submitRegister(name, password) {
            postData('/account/register', { name, password })
                .then(res => res.json())
                .then(data => {
                    if (data.error) return errorToast(data.error);
                    infoToast(data.message);
                    ws.connect();
                })
                .catch(error => errorToast(error));
        }

        return {
            submitRegister,
        }
    },
);

function Register(args) {
    const {
        submitRegister,
    } = args;

    const { password, confirm, name } = this.state;

    const registerSubmit = (event) => {
        event.preventDefault();
        submitRegister(name, password);
    }

    const registerConfirm = () =>
        password === confirm;

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

    return (
        <div class="login">
            <label for="username">Username</label>
            <input
                class="login-input"
                type="email"
                placeholder="username"
                value={this.state.name}
                onInput={linkState(this, 'name')}
            />
            <label for="password">Password - min 12 chars</label>
            <input
                class="login-input"
                type="password"
                placeholder="password"
                value={this.state.password}
                onInput={linkState(this, 'password')}
            />
            <label for="confirm">Confirm Password</label>
            <input
                class={`${registerConfirm() ? '' : 'red'} login-input`}
                type="password"
                placeholder="confirm"
                value={this.state.confirm}
                onInput={linkState(this, 'confirm')}
            />
            <button
                class="login-btn"
                disabled={registerDisabled()}
                onClick={registerSubmit}>
                Register
            </button>
        </div>
    );
}

module.exports = addState(Register);
