import * as React from 'react'
import { Form, Input, Icon } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { compose } from 'react-apollo'

export interface Props {
  value: string
  onSearchEnter: (term: string) => void
}

interface IState {
  focused: boolean
}

class SearchInput extends React.Component<Props & FormComponentProps, IState> {
  state: IState = {
    focused: false,
  }

  public render() {
    const { focused } = this.state
    const { getFieldDecorator } = this.props.form

    return (
      <Form style={{ height: '60px', paddingTop: '10px', minWidth: '400px' }}>
        <Form.Item>
          {getFieldDecorator('searchTerm', {
            rules: [
              {
                message:
                  'openscript search [argument] - enter search-term argument',
                required: true,
              },
            ],
            initialValue: this.props.value,
          })(
            <Input
              size="large"
              className="terminal-input"
              onPressEnter={this.onEnter}
              style={{ opacity: focused ? 1 : 0.7 }}
              onFocus={this.onFocus}
              onBlur={this.onBlur}
              placeholder={' e.g. "install nvm"'}
              addonBefore={<Icon type="search" />}
            />
          )}
        </Form.Item>
      </Form>
    )
  }

  private onEnter = () => {
    const { validateFields } = this.props.form
    validateFields((err, values) => {
      if (err) return

      const { searchTerm } = values
      this.props.onSearchEnter(searchTerm)
    })
  }

  private onFocus = () => {
    this.setState({ focused: true })
  }
  private onBlur = () => {
    this.setState({ focused: false })
  }
}

export default compose(Form.create({ name: 'search' }))(SearchInput)
