import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import {TextInput} from './form/TextInput';
import {Block} from './Block';
import {Icon} from './Icon';

export class Filter extends React.Component {
    static propTypes = {
        onChange: PropTypes.func.isRequired,
        id: PropTypes.string,
        testAutomationId: PropTypes.string,
        wrapperClassName: PropTypes.string,
        selectOnFocus: PropTypes.bool,
        onFocus: PropTypes.func,
        ariaLabel: PropTypes.string
    };

    static defaultProps = {
        id: null,
        testAutomationId: 'fieldFilter',
        wrapperClassName: '',
        selectOnFocus: false,
        onFocus: () => {},
        ariaLabel: 'TRANSLATE:SEARCH'
    };

    constructor(props, context) {
        super(props, context);

        this.handleChange = this.handleChange.bind(this);
        this.handleFocusField = this.handleFocusField.bind(this);
    }

    handleChange(event) {
        this.props.onChange(this.refs.searchField.getValue());
    }

    focus() {
        this.refs.searchField.focus();
    }

    handleFocusField(event) {
        if (this.props.selectOnFocus) {
            event.target.select();
        }

        if (this.props.onFocus) {
            this.props.onFocus(event);
        }
    }

    render() {
        let {wrapperClassName, ariaLabel, id, ...props} = this.props;

        Object.assign(props, {
            'aria-label': props['aria-label'] || ariaLabel,
            id: props['controlId'] || id
        });

        return (
            <Block className="rc-filter" noOffset>
                <TextInput
                    {...props}
                    wrapperClassName={classnames('form-group', wrapperClassName)}
                    ref="searchField"
                    onChange={this.handleChange}
                    onFocus={this.handleFocusField}
                />
                <Icon name="search" />
            </Block>
        );
    }
}
