import _ from 'lodash';
import React from 'react';
import { Statuses } from 'constants/Restore';
import StoreMixin from 'lib/StoreMixin';
import { i18n, formatDateTime } from 'lib/i18n';
import Url from 'lib/Url';
import notify from 'services/notify';

import RestoreActions from 'actions/Restore';
import RestoreStore from 'stores/Restore';
import ConfigStore from 'stores/Config';

import Button from 'lego-ui/Button';
import ButtonLink from 'lego-ui/ButtonLink';
import LastCheck from './LastCheck';
import Toggle from './Toggle';
import Instructions from './Instructions';

export default React.createClass({

    mixins: [StoreMixin],

    getStoreState() {
        const { props } = this;

        const initialState = {
            state: props.state,
            lastCheck: props.last_check || {},
            methods: props.methods,
            selectedMethod: _.get(props.methods, [0, 'method']),
            owned: props.owned,
        };

        const ownershipStatus = RestoreStore.getOwnershipStatus();

        const nextState = {
            state: RestoreStore.getCurrentCheck().state,
            lastCheck: ownershipStatus.last_check || {},
            methods: ownershipStatus.methods,
            owned: ownershipStatus.owned,
        };

        return _.extend(initialState, this.state, nextState);
    },

    componentDidMount() {
        this.subscribe(RestoreStore);

        if (this.props.state === Statuses.IN_PROGRESS) {
            RestoreActions.trackStatus(this.props.restore_id);
        }
    },

    componentWillUnmount() {
        RestoreActions.stopStatusTracking();
    },

    _startOwnershipCheck() {
        RestoreActions.checkOwnership(this.props.restore_id, {
            verification_type: this.state.selectedMethod,
        })
            .then(response => {
                if (response.code) {
                    const errorMessage = i18n(`restore.domain_ownership.error.${response.code}`) ||
                        i18n('restore.domain_ownership.error.generic');

                    return notify(errorMessage, 'error');
                }

                notify(i18n('restore.domain_ownership.status.check_started'), 'success');
                RestoreActions.trackStatus(this.props.restore_id);
            });
    },

    render() {
        const { props, state } = this;

        if (!props.domain || props.code === Statuses.NOT_FOUND) {
            return (
                <div className="domain-ownership" data-state={Statuses.NOT_FOUND}>
                    <div className="domain-ownership__state">
                        {i18n(`restore.domain_ownership.status.${Statuses.NOT_FOUND}`)}
                    </div>
                    <div className="domain-ownership__buttons">
                        <ButtonLink
                            to={Url.getPath('/restore/new')}
                            text={i18n('restore.new_request')}
                        />
                        <ButtonLink
                            to={ConfigStore.getHelpUrl('ui.help.restore_feedback')}
                            text={i18n('restore.action.report')}
                        />
                    </div>
                </div>
            );
        }

        const title = (
            <h1 className="domain-ownership__title">
                {i18n('restore.domain_ownership.title', { domain: props.domain })}
            </h1>
        );

        if (state.state === Statuses.SUCCESS) {
            return (
                <div className="domain-ownership" data-state={state.state}>
                    {title}
                    <div className="domain-ownership__state">
                        {i18n(`restore.list.status.${state.state}`)}
                    </div>
                    <div className="domain-ownership__buttons">
                        <ButtonLink
                            to="/"
                            target="_self"
                            text={i18n('restore.action.to_connect')}
                        />
                    </div>
                </div>
            );
        }

        if (state.state !== Statuses.IN_PROGRESS) {
            const message = i18n('restore.invalid_answers.title', {
                domain: props.domain,
            });
            let details;

            if (state.state === Statuses.INVALID_ANSWERS) {
                details = (
                    <div className="domain-ownership__state">
                        {i18n('restore.invalid_answers.content')}
                    </div>
                );
            }

            return (
                <div className="domain-ownership" data-state={state.state}>
                    <h1
                        className="domain-ownership__title"
                        dangerouslySetInnerHTML={{ __html: message }}
                    />
                    {details}
                    <div className="domain-ownership__buttons">
                        <ButtonLink
                            to={Url.getPath('/restore/new')}
                            text={i18n('restore.new_request')}
                        />
                        <ButtonLink
                            to={ConfigStore.getHelpUrl('ui.help.restore_feedback')}
                            text={i18n('restore.action.to_support')}
                        />
                    </div>
                </div>
            );
        }

        if (state.owned) {
            return (
                <div className="domain-ownership" data-state={state.state}>
                    {title}
                    <div className="domain-ownership__state">
                        {i18n('restore.domain_ownership.status.almost_done')}
                    </div>
                </div>
            );
        }

        const description = i18n('restore.domain_ownership.description', {
            domain: props.domain,
            date: formatDateTime(props.expires_at),
        });

        return (
            <div className="domain-ownership">
                {title}
                <div
                    className="domain-ownership__description"
                    dangerouslySetInnerHTML={{ __html: description }}
                />
                <div className="domain-ownership__tip">
                    {i18n('restore.domain_ownership.dns_verification_tip')}
                </div>
                <LastCheck
                    {...state.lastCheck}
                />
                <Toggle
                    {...state}
                    onChange={selectedMethod => this.setState({ selectedMethod })}
                    val={state.selectedMethod}
                />
                <Instructions
                    domain={props.domain}
                    {...state}
                />
                <div className="domain-ownership__buttons">
                    <Button
                        view="action"
                        text={i18n('domain.action.start_ownership_check')}
                        onClick={this._startOwnershipCheck}
                    />
                </div>
            </div>
        );
    },

});
