import React from 'react'
import styles from './index.module.less'
import { useStore } from '../../store'

import { Select } from 'antd'
import { mergeSameTypeSimilarQuery, transformOptionToValueOption } from '../../utils/searchSelect'
import { SimilarQueryItem } from '../../types/searchSelect'

const SearchSelect: React.FC = () => {
  const [store, useObserver] = useStore()

  const { pullSimilarQuery, setQueryAndSearch } = store.main

  return useObserver(() => {
    const { query, similarQuery } = store.main

    const value = transformOptionToValueOption(query)
    const options = searchSelectDropdownRender(similarQuery)

    return (
      <Select
        className={styles['nd-search-select-for-all']}
        placeholder="请输入要检索的关键词"
        mode="multiple"
        loading={false}
        labelInValue={true}
        filterOption={false}
        notFoundContent={null}
        onSearch={pullSimilarQuery}
        value={value}
        onChange={setQueryAndSearch}
        onFocus={undefined}
      >
        {options}
      </Select>
    )
  })
}

function searchSelectDropdownRender(similarQuery: SimilarQueryItem[]) {
  const options = mergeSameTypeSimilarQuery(similarQuery)

  return (
    <React.Fragment>
      {options.map(({ typeName, group }) => (
        <Select.OptGroup label={typeName} key={typeName}>
          {group.map(({ q }) => (
            <Select.Option
              key={`${typeName}:${q}`}
              value={`${typeName}:${q}`}
              title={`${typeName}:${q}`}
            >
              {q}
            </Select.Option>
          ))}
        </Select.OptGroup>
      ))}
    </React.Fragment>
  )
}

export default SearchSelect
