import { Row, Col } from 'antd/lib/grid'
import { Option, Select } from 'components/Select/Select'
import React from 'react'
import { useEffect } from 'react'
import { useState } from 'react'

interface Props {
  value: number // seconds
  hourFilter?: (value: number) => boolean
  minuteFilter?: (value: number) => boolean
  secondsFilter?: (value: number) => boolean
  onChange(value: number): void
}

interface FilterTime {
  minutes: number
  seconds: number
}

const MINUTES = Array.from(Array(61).keys())
const SECONDS = Array.from(Array(61).keys())

const SelectTimeDuration: React.FC<Props> = ({
  value,
  minuteFilter = () => true,
  secondsFilter = () => true,
  onChange
}) => {
  const [filter, setFilter] = useState<FilterTime>({
    minutes: 0,
    seconds: 0
  })

  useEffect(() => {
    if (!value) return
    setFilter(formatSecondToTime(value))
  }, [value])

  useEffect(() => {
    onChange(formatTimeToSeconds(filter))
  }, [filter])

  const formatSecondToTime = (seconds: number): FilterTime => {
    const hours = Math.floor(seconds / 3600)
    const minutes = hours * 60 + Math.floor((seconds % 3600) / 60)
    const sec = seconds - minutes * 60
    return {
      minutes,
      seconds: sec
    }
  }

  const formatTimeToSeconds = (time: FilterTime): number => {
    return time.minutes * 60 + time.seconds
  }
  const onChangeMinutes = (minutes: number) => {
    setFilter(preState => ({ ...preState, minutes }))
  }

  const onChangeSeconds = (seconds: number) => {
    setFilter(preState => ({ ...preState, seconds }))
  }

  return (
    <React.Fragment>
      <Row gutter={[16, 16]} className="select-duration">
        <Col xs={24} md={12} lg={12}>
          <Select value={filter.minutes} onChange={onChangeMinutes}>
            {MINUTES.filter(minuteFilter).map((n, i) => (
              <Option key={i} value={n}>
                {`${n} min(s)`}
              </Option>
            ))}

            {/* auto gererate option out of range */}
            {!MINUTES.filter(minuteFilter).includes(filter.minutes) && (
              <Option key={filter.minutes} value={filter.minutes}>
                {`${filter.minutes} min(s)`}
              </Option>
            )}
          </Select>
        </Col>
        <Col xs={24} md={12} lg={12}>
          <Select value={filter.seconds} onChange={onChangeSeconds}>
            {SECONDS.filter(secondsFilter).map((n, i) => (
              <Option key={i} value={n}>
                {`${n} second(s)`}
              </Option>
            ))}

            {/* auto gererate option out of range */}
            {!SECONDS.filter(secondsFilter).includes(filter.seconds) && (
              <Option key={filter.seconds} value={filter.seconds}>
                {`${filter.seconds} second(s)`}
              </Option>
            )}
          </Select>
        </Col>
      </Row>
    </React.Fragment>
  )
}

export default SelectTimeDuration
