import React, { useState, useCallback } from 'react'
import styles from './index.module.less'
import { RangeUnitFilter, RangeWithIndex } from '../../types/searchSelect'
import { store } from '../../store'

import FilterRightHelper from '../FilterRightHelper'
import RangeFilterInputItem from '../RangeFilterInputItem'

type ComponentProps = {
  filter: RangeUnitFilter
}

const RangeFilter: React.FC<ComponentProps> = ({ filter }) => {
  const [rangeValue, setRangeValue] = useState<RangeWithIndex[]>([])
  const usefulRangeValue: RangeWithIndex[] = rangeValue.filter(({ range }) => {
    const { low, high } = range.range

    return Number.isFinite(low!) || Number.isFinite(high!)
  })

  const { values = [] } = filter.tag

  const handleChange = useCallback(
    (range, index) => {
      const currentRangeValue = [...rangeValue]
      const findIndex = currentRangeValue.findIndex(({ index: _i }) => _i === index)

      if (findIndex !== -1) currentRangeValue.splice(findIndex, 1)

      setRangeValue([...currentRangeValue, { range, index }])
    },
    [rangeValue, setRangeValue]
  )

  const submit = useCallback(() => {
    const { tag } = filter
    const values = usefulRangeValue.map(({ range }) => range)
    store.main.appendFilter({
      ...filter,
      tag: {
        ...tag,
        values,
      },
    })
  }, [filter, usefulRangeValue])

  return (
    <React.Fragment>
      <div className={styles['analysis-range-filter-container']}>
        {values.map((range, index) => (
          <RangeFilterInputItem
            key={range.name}
            rangeItem={rangeValue.find(({ index: _i }) => _i === index)?.range || range}
            onChange={_ => handleChange(_, index)}
          />
        ))}
      </div>

      <FilterRightHelper
        type={usefulRangeValue.length ? 'SUBMIT_BTN' : 'SUBMIT_BAN'}
        onClick={submit}
      />
    </React.Fragment>
  )
}

export default RangeFilter
