import React from 'react';
import block from 'bem-cn';
import { Button } from 'lego-on-react';
import { i18n } from 'i18n2';
import InlineError from 'components2/InlineError';
import './index.css';

const b = block('form');

const Form = ({ children, cls, type, onSubmit }) => {
    function onFormSubmit(e) {
        e.preventDefault();

        if (onSubmit) {
            onSubmit();
        }
    }

    return (
        <form
            className={b({ type }).mix(cls)}
            onSubmit={onFormSubmit}
        >
            {children}
        </form>
    );
};

Form.Field = ({ children, errors, name, cls }) => {
    let fieldErrors = errors && errors[name];

    return (
        <div
            className={b('field', {
                name: name && name.replace(/_/g, '-'),
            }).mix(cls)}
        >
            {children}
            {Boolean(fieldErrors) && (
                <div className={b('field-error', { visible: Boolean(fieldErrors.length) })}>
                    {fieldErrors.map((err, i) => (
                        <div
                            className={b('field-error-text')}
                            key={i}
                        >
                            {err}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
};

Form.Label = ({ children, cls, required }) => (
    <div className={b('label', { required }).mix(cls)}>
        {children}
    </div>
);

Form.Value = ({ children, cls }) => (
    <div className={b('value').mix(cls)}>
        {children}
    </div>
);

Form.Error = ({ children, cls }) => (
    <InlineError cls={b('error').mix(cls)}>
        {children}
    </InlineError>
);

Form.Actions = ({
    cls,
    onSubmit,
    onCancel,
    submitCaption = i18n('common.action.save'),
    cancelCaption = i18n('common.action.cancel'),
    submitDisabled = false,
}) => (
    <div className={b('actions').mix(cls)}>
        <Button
            theme="action"
            type="action"
            size="m"
            cls={b('button', { type: 'submit' })}
            disabled={submitDisabled}
            onClick={onSubmit}
        >
            {submitCaption}
        </Button>
        <Button
            theme="pseudo"
            size="m"
            cls={b('button', { type: 'cancel' })}
            onClick={onCancel}
        >
            {cancelCaption}
        </Button>
    </div>
);

export default Form;
