import React, { useCallback } from 'react'
import { Unit } from '../../types/searchSelect'

import { Select } from 'antd'

type ComponentProps = {
  value: Unit
  options: Unit[]
  onChange: (unit: Unit) => any
}

const RangeFilterUnitSelect: React.FC<ComponentProps> = ({
  value: { quantity, unit },
  options,
  onChange,
}) => {
  const handleChange = useCallback(
    value => {
      const [quantity, unit] = value.split(':')

      const target = options.find(({ quantity: _q, unit: _u }) => _q === quantity && _u === unit)!

      onChange(target)
    },
    [options, onChange]
  )

  return (
    <Select value={`${quantity}:${unit}`} onChange={handleChange}>
      {options.map(({ quantity, unit }) => (
        <Select.Option key={quantity + unit} value={`${quantity}:${unit}`}>
          {`${quantity}${unit}`}
        </Select.Option>
      ))}
    </Select>
  )
}

export default RangeFilterUnitSelect
