import PropTypes from 'prop-types';
import React from 'react';
import { block } from 'bem-cn';

import './captcha.css';

import { TextInput, Link, Spin, Image } from 'lego-on-react';
const bCaptcha = block('captcha');

const Captcha = React.createClass({

    _onChange(text) {
        this.props.onChange(text);
    },

    render() {
        const { src, text, onRefresh, loading, labels: { placeholder, label, refresh } } = this.props;
        let content;

        if (!loading) {
            content = <Image url={src} />;
        } else {
            content = (
                <Spin
                    cls={bCaptcha('loading')}
                    position="center"
                    size="s"
                    progress
                />
            );
        }

        return (
            <div className={bCaptcha()}>
                <div className={bCaptcha('label')}>
                    {label}
                </div>
                <div className={bCaptcha('content')}>
                    <div className={bCaptcha('image')}>
                        {content}
                    </div>
                    <div className={bCaptcha('controls')}>
                        <Link
                            theme="pseudo"
                            type="pseudo"
                            cls={bCaptcha('refresh')}
                            pseudo
                            onClick={onRefresh}
                            disabled={loading}
                        >
                            {refresh}
                        </Link>
                    </div>
                    <TextInput
                        theme="normal"
                        size="m"
                        cls={bCaptcha('input')}
                        text={text}
                        autoComplete={false}
                        onChange={this._onChange}
                        placeholder={placeholder}
                    />
                </div>
            </div>
        );
    },

});

Captcha.propTypes = {
    src: PropTypes.string,
    text: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    onRefresh: PropTypes.func.isRequired,
    loading: PropTypes.bool,
    labels: PropTypes.shape({
        placeholder: PropTypes.string.isRequired,
        label: PropTypes.string.isRequired,
        refresh: PropTypes.string.isRequired,
    }),
};

export default Captcha;
