import PropTypes from 'prop-types';
import React, { Component } from 'react';

import Loader from 'ui-components/lib/Loader';
import Form from 'ui/Form';
import Toggle from 'lego-ui/Toggle';

import ConfigStore from 'stores/Config';

import template from 'lib/template';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import InviteLink from './InviteLink';

import './add-invite-link.css';

class AddInviteLink extends Component {
    _renderLink() {
        const { code, active, loading, onChange } = this.props;

        let linkContent;

        if (code) {
            const inviteLink = template.build(ConfigStore.get('org.invite'), {
                host: Url.getHost(),
                code,
            });

            linkContent = <InviteLink inviteLink={inviteLink} />;
        } else {
            linkContent = (
                <div className="add-invite-link__text">
                    {i18n('department.add_user_by_link')}
                </div>
            );
        }

        return (
            <div className="add-invite-link__link">
                <Toggle
                    disabled={loading}
                    onChange={onChange}
                    checked={active}
                />
                <div className="add-invite-link__code">
                    {linkContent}
                </div>
            </div>
        );
    }

    render() {
        const { loading, error, initing } = this.props;

        return (
            <div className="add-invite-link">
                <Loader visible={loading} />
                {!initing && this._renderLink()}
                <Form.Error value={error} mod="standalone" />
            </div>
        );
    }
}

AddInviteLink.propTypes = {
    onChange: PropTypes.func.isRequired,
    code: PropTypes.string,
    loading: PropTypes.bool.isRequired,
    initing: PropTypes.bool.isRequired,
    error: PropTypes.string,
};

export default AddInviteLink;
