import { Input, Select } from 'antd'
import React, { useEffect, useState } from 'react'

const { Option } = Select

interface SearchBarProps {
  defaultValue: { [key: string]: string | undefined }
  options: string[]
  labels?: string[]
  fetcher: (
    query: { [key: string]: string | undefined } | null
  ) => Promise<void>
}

function SearchBar({
  defaultValue,
  options,
  fetcher,
  labels = []
}: SearchBarProps) {
  const defaultQuery =
    Object.keys(defaultValue).find((key) => !!defaultValue[key]) || options[0]
  const [queryOption, setQueryOption] = useState(defaultQuery)

  useEffect(() => {
    setQueryOption(defaultQuery)
  }, [defaultQuery])

  const handleOptionChange = (value: string) => {
    setQueryOption(value)
  }

  const handleSearch = (value: string) => {
    fetcher(value ? { [queryOption]: value.trim() } : null)
  }

  return (
    <Input.Group compact className="list-search-bar-container">
      <Select
        style={{ width: '9rem' }}
        defaultValue={queryOption}
        onChange={handleOptionChange}
      >
        {options.map((o, idx) => {
          return (
            <Option key={o} value={o}>
              {labels[idx] === undefined ? o : labels[idx]}
            </Option>
          )
        })}
      </Select>
      <Input.Search
        style={{ width: '60%' }}
        defaultValue={defaultValue[defaultQuery] || ''}
        onSearch={handleSearch}
        allowClear
      />
    </Input.Group>
  )
}

export default React.memo(SearchBar) as typeof SearchBar
