// 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 submitRecover(email) {
            postData('/account/recover', { email })
                .then(res => res.json())
                .then(data => {
                    if (data.error) return errorToast(data.error);
                    infoToast(data.message);
                })
                .catch(error => errorToast(error));
        }

        return {
            submitRecover,
        }
    },
);

const EMAIL_SUBJECT = name => `
account support: ${name || 'CHANGEME'}
`;

const EMAIL_BODY = `
---
include some details regarding your account. ie.
- account name
- construct names
---
`;

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

    const { email } = this.state;

    const buttonSubmit = (event) => {
        event.preventDefault();
        submitRecover(email);
        // this.setState({ email: '' });
    };

    const buttonDisabled = () => {
        return !email;
    };

    const supportLink = encodeURI(`mailto:humans@mnml.gg?subject=${EMAIL_SUBJECT(email)}&body=${EMAIL_BODY}`);

    return (
        <div class="login">
            <p>
                Send a recovery email to your account's confirmed email address.
            </p>
            <p>
                If you have not set and confirmed an email address for your account
                please contact support.
            </p>
            <label for="username">Account Email</label>
            <input
                class="login-input"
                type="email"
                placeholder="player@mnml.gg"
                value={email}
                onInput={linkState(this, 'email')}
            />
            <button
                class="login-btn"
                disabled={buttonDisabled()}
                onClick={buttonSubmit}> Send Recovery Email
            </button>
            <button>
                <a href={supportLink}>✉ support</a>
            </button>
        </div>
    );
}

module.exports = addState(Register);
