// @flow
import React from 'react'
import debounce from 'lodash.debounce'
import { Icon } from '@siteone/pagebuilder-ui'
import styles from './styles.scss'

type Props = {
  handleSerachParametersChange: Function,
  serchConfig: Array<Object>,
}

type State = {
  searchParameters: Object,
}

class SearchBar extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props)

    this.state = {
      searchParameters: {},
    }
    this.handleSerachParametersChange = debounce(props.handleSerachParametersChange, 150, { trailing: true })
  }

  handleTextInputValueChange = (event: SyntheticInputEvent<HTMLInputElement>) => {
    const { searchParameters } = this.state
    const newSearchParameters = {
      ...searchParameters,
      [event.target.name]: event.target.value,
    }
    this.setState({ searchParameters: newSearchParameters })
    this.handleSerachParametersChange(newSearchParameters)
  }

  renderInput = (inputConfig: Object) => {
    switch (inputConfig.type) {
      case 'text':
        return this.renderTextInput(inputConfig)
      default:
        console.error(`Invalid input type: "${inputConfig.type}"`)
        break
    }
    return false
  }

  renderTextInput = (inputConfig: Object) => {
    const { searchParameters } = this.state
    const value = searchParameters[inputConfig.name] || ''
    return (
      <div className={styles.container} key={inputConfig.name}>
        <input
          type="text"
          placeholder={inputConfig.placeholder}
          name={inputConfig.name}
          value={value}
          onChange={this.handleTextInputValueChange}
          className={styles.input}
        />
        <Icon
          name="navigation/Search"
          className={styles.icon}
          
        />
      </div>
    )
  }

  render() {
    const { serchConfig } = this.props
    return <div>{serchConfig.map(inputConfig => this.renderInput(inputConfig))}</div>
  }
}

export default SearchBar
