import React, { Component } from 'react'
import classNames from 'classnames'

type Props = {
  className?: string
  disabled?: boolean
  id: string
  label: string
  name?: string
  onInput?: (value: any) => void
  onChange?: (value: string) => void
  options: {
    value: string
    text: string
  }[]
  revealValidationMessage?: boolean
  style?: object
  tabIndex?: number
  validationMessage?: string
  value?: string
  dataTestId?: string
}
class SelectBlock extends Component<Props> {
  constructor(props: Props) {
    super(props)
    this.state = {
      hasChanged: false,
      isFocused: false,
    }
    this.handleInput(props.value || '')
  }

  handleInput = (value: any) => {
    const { onInput } = this.props
    if (onInput) onInput(value)
  }

  onFocus = () => {
    this.setState({
      isFocused: true,
    })
  }

  onBlur = () => {
    this.setState({
      isFocused: false,
    })
  }

  onChange = (e: any) => {
    this.setState({
      hasChanged: true,
    })
    const { onChange } = this.props
    if (onChange) onChange(e.target.value)
    this.handleInput(e.target.value)
  }

  render() {
    const {
      className,
      disabled,
      id,
      label,
      name,
      options,
      revealValidationMessage,
      style,
      tabIndex,
      validationMessage,
      value,
      dataTestId,
    } = this.props

    const { hasChanged, isFocused }: any = this.state

    const showError =
      validationMessage && (hasChanged || revealValidationMessage)
    const displayLabel = showError ? validationMessage : label

    const wrapperClass = classNames({
      'ui-input__select-wrapper': true,
      'ui-input__select-wrapper--error': !!showError,
      'ui-input__select-wrapper--focused': isFocused,
      'ui-input__select-wrapper--has-value': !!value,
      [className!]: !!className,
    })

    return (
      <div className={wrapperClass} style={style}>
        {displayLabel && (
          <label
            className="ui-input__select-label"
            htmlFor={id || name}
            data-text={displayLabel}
          >
            {displayLabel}
          </label>
        )}
        <select
          className="ui-input__select"
          disabled={disabled}
          id={id}
          name={name}
          onBlur={this.onBlur}
          onChange={this.onChange}
          onFocus={this.onFocus}
          tabIndex={tabIndex}
          value={value}
          data-testid={dataTestId}
        >
          <option
            className="ui-input__select-option ui-input__select-option--hidden"
            disabled
            value=""
          />
          {options &&
            options.map((o, i) => (
              <option
                className="ui-input__select-option"
                key={i}
                value={o.value}
              >
                {o.text}
              </option>
            ))}
        </select>
      </div>
    )
  }
}

export default SelectBlock
