const preact = require('preact');
const { Component } = require('preact')
const { connect } = require('preact-redux');
const linkState = require('linkstate').default;

const SpawnButton = require('./spawn.button');

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

const addState = connect(
    function receiveState(state) {
        const {
            account,
            subscription,
            email,
            ping,
            ws,
        } = state;


        function sendSetPassword(current, password) {
            postData('/account/password', { current, password })
                .then(res => res.json())
                .then(data => {
                    if (data.error) return errorToast(data.error);
                    infoToast('Password changed. Reloading...')
                    setTimeout(() => window.location.reload(), 5000);
                })
                .catch(error => errorToast(error));
        }

        function sendSetEmail(email) {
            postData('/account/email', { email })
                .then(res => res.json())
                .then(data => {
                    if (data.error) return errorToast(data.error);
                    infoToast('Email set. Please confirm your address.');
                    return true;
                })
                .catch(error => errorToast(error));
        }

        function logout() {
            postData('/account/logout').then(() => window.location.reload(true));
        }


        function sendConstructSpawn(name) {
            return ws.sendMtxConstructSpawn(name);
        }

        function sendSubscriptionEnding(enabled) {
            return ws.sendSubscriptionEnding(enabled);
        }

        return {
            account,
            subscription,
            ping,
            email,
            logout,
            sendSetPassword,
            sendSetEmail,
            sendConstructSpawn,
            sendSubscriptionEnding,
        };
    },
);


class AccountStatus extends Component {
    constructor(props) {
        super(props);

        this.state = {
            passwordState: { current: '', password: '', confirm: ''},
            emailState: null,
            unsubState: false,
        };
    }

    render(args, state) {
        const {
            account,
            subscription,
            ping,
            email,
            logout,
            sendSetEmail,
            sendSetPassword,
            sendConstructSpawn,
            sendSubscriptionEnding,
        } = args;

        const {
            passwordState,
            emailState,
            unsubState,
        } = state;

        if (!account) return null;

        const passwordsEqual = () =>
            passwordState.password === passwordState.confirm;

        const setPasswordDisabled = () => {
            const { current, password, confirm } = passwordState;
            return !(passwordsEqual() && password && current && confirm);
        }

        const tlClick = e => {
            e.stopPropagation();
            return this.setState({ unsubState: false });
        }

        const subInfo = () => {
            const unsubBtn = () => {
                if (!subscription) return false;

                // resub button
                if (subscription.cancel_at_period_end) {
                    return <button class='stripe-btn' onClick={() => sendSubscriptionEnding(false)}>Resubscribe</button>
                }

                const classes = `unsub ${unsubState ? 'confirming' : ''}`;
                const text = unsubState ? 'Confirm' : 'Unsubscribe'
                return <button class={classes} onClick={unsub}>{text}</button>
            }

            const unsub = e => {
                if (unsubState) {
                    return sendSubscriptionEnding(true);
                }

                e.stopPropagation();
                return this.setState({ unsubState: true });
            }

            if (!subscription) return false;
            return <div>
                <h3>Subscription</h3>
                <dl>
                    <dt>Period End</dt>
                    <dd>{new Date(subscription.current_period_end * 1000).toString()}</dd>
                    <dt>Status</dt>
                    <dd>{subscription.cancel_at_period_end ? 'Disabled' : 'Active'}</dd>
                </dl>
                {unsubBtn()}
            </div>;
        }

        return (
            <section class='account top' onClick={tlClick}>
                <div>
                    {subInfo()}
                </div>
                <div>
                    <label for="email">Email Settings:</label>
                    <dl>
                        <dt>Recovery Email</dt>
                        <dd>{email ? email.email : 'No email set'}</dd>
                        <dt>Status</dt>
                        <dd>{email && email.confirmed ? 'Confirmed' : 'Unconfirmed'}</dd>
                    </dl>
                    <input
                        class="login-input"
                        type="email"
                        name="email"
                        value={emailState}
                        onInput={linkState(this, 'emailState')}
                        placeholder="recovery@email.tld"
                    />
                    <button onClick={() => sendSetEmail(emailState)}>Update</button>
                </div>
                <div>
                    <label for="current">Password:</label>
                    <input
                        class="login-input"
                        type="password"
                        name="current"
                        value={passwordState.current}
                        onInput={linkState(this, 'passwordState.current')}
                        placeholder="current"
                    />
                    <input
                        class="login-input"
                        type="password"
                        name="new"
                        value={passwordState.password}
                        onInput={linkState(this, 'passwordState.password')}
                        placeholder="new password"
                    />
                    <input
                        class="login-input"
                        type="password"
                        name="confirm"
                        value={passwordState.confirm}
                        onInput={linkState(this, 'passwordState.confirm')}
                        placeholder="confirm"
                    />
                    <button
                        disabled={setPasswordDisabled()}
                        onClick={() => sendSetPassword(passwordState.current, passwordState.password)}>
                        Set Password
                    </button>
                </div>
                <div>
                    <figure>
                        <figcaption>spawn new construct</figcaption>
                        <button onClick={() => sendConstructSpawn()} type="submit">
                            ¤50
                        </button>
                    </figure>
                    <button onClick={() => logout()}>Logout</button>
                    <button><a href={`mailto:humans@mnml.gg?subject=Account%20Support:%20${account.name}`}>✉ support</a></button>
                </div>
            </section>
        );
    }
}

module.exports = addState(AccountStatus);
