import React, { useState, useCallback } from 'react'
import styles from './index.module.less'
import { RangeUnitTagValueItem, LowAndHighRange, Unit } from '../../types/searchSelect'

import RangeFilterHistogram from '../RangeFilterHistogram'
import RangeFilterLowHighInput from '../RangeFilterLowHighInput'
import RangeFilterUnitSelect from '../RangeFilterUnitSelect'

type ComponentProps = {
  rangeItem: RangeUnitTagValueItem
  onChange: (range: RangeUnitTagValueItem) => any
}

const RangeFilterInputItem: React.FC<ComponentProps> = ({ rangeItem, onChange }) => {
  const { name, range, unit, unitOptions = [], histogram } = rangeItem
  const [tempRange, setTempRange] = useState<LowAndHighRange | undefined>(undefined)
  const [tempUnit, setTempUnit] = useState<Unit | undefined>(undefined)

  const getRangeAndUnitByHistogramIndex = useCallback(
    index => {
      const { buckets = [], unit } = histogram!

      return {
        range: buckets[index].range,
        unit,
      }
    },
    [histogram]
  )

  const handleTempChange = useCallback(
    index => {
      const { range, unit } = getRangeAndUnitByHistogramIndex(index)

      setTempRange(range)
      setTempUnit(unit)
    },
    [getRangeAndUnitByHistogramIndex, setTempRange, setTempUnit]
  )

  const handleRecover = useCallback(() => {
    setTempRange(undefined)
    setTempUnit(undefined)
  }, [setTempRange, setTempUnit])

  const handleChange = useCallback(
    index => {
      const { range, unit } = getRangeAndUnitByHistogramIndex(index)

      onChange({
        ...rangeItem,
        range,
        unit,
      })
    },
    [rangeItem, getRangeAndUnitByHistogramIndex, onChange]
  )

  const handleRangeChange = useCallback(
    range => {
      onChange({
        ...rangeItem,
        range,
      })
    },
    [rangeItem, onChange]
  )

  const handleUnitChange = useCallback(
    unit => {
      onChange({
        ...rangeItem,
        unit,
      })
    },
    [rangeItem, onChange]
  )

  return (
    <div className={styles['analysis-range-filter-input-item']}>
      <div className="range-name">{name || '范围'}</div>
      <div className="range-value">
        <RangeFilterLowHighInput range={tempRange || range} onChange={handleRangeChange} />

        <RangeFilterUnitSelect
          value={tempUnit || unit}
          options={unitOptions}
          onChange={handleUnitChange}
        />

        {histogram && (
          <RangeFilterHistogram
            histogram={histogram}
            onTempChange={handleTempChange}
            onChange={handleChange}
            onRecover={handleRecover}
          />
        )}
      </div>
    </div>
  )
}

export default RangeFilterInputItem
