import React, { useEffect, useRef } from 'react'

import { LeftOutlined, RightOutlined } from '@ant-design/icons'

import TimeWindowSelectController from './SelectController'
import { TimeRange } from './types'

export type TimeWindowSelectProps = {
  startTime: number
  timeSpans?: TimeRange[]
  timeWindow?: TimeRange | null
  onTimeWindowChange?: (t: TimeRange) => void
  onTimelineChange?: (t: TimeRange) => void
  onNext?: () => void
  onPre?: () => void
}

const TimeWindowSelect: React.FC<TimeWindowSelectProps> = ({
  startTime,
  timeSpans = [],
  timeWindow = null,
  onTimeWindowChange,
  onTimelineChange,
  onNext,
  onPre
}) => {
  const wsRef = useRef(null)
  const wscRef = useRef<TimeWindowSelectController>()

  useEffect(() => {
    if (wsRef.current) {
      wscRef.current = new TimeWindowSelectController(wsRef.current, startTime)
      wscRef.current.onTimeWindowChange = function (t) {
        onTimeWindowChange?.(t)
      }
      wscRef.current.onTimelineChange = function (t) {
        onTimelineChange?.(t)
      }
    }
    return () => wscRef.current?.cleanup()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => {
    wscRef.current?.resetStartTime(startTime)
  }, [startTime])

  useEffect(() => {
    wscRef.current?.setTimeSpans(timeSpans)
  }, [timeSpans])

  useEffect(() => {
    wscRef.current?.setSelectedTimeWindow(timeWindow)
  }, [timeWindow])

  return (
    <div
      ref={wsRef}
      className='w-full h-20 rounded-lg bg-white overflow-hidden border border-gray-200 border-solid relative'
    >
      <div className='absolute h-full left-0 flex items-center px-1 text-gray-500'>
        <LeftOutlined onClick={onPre} />
      </div>
      <div className='absolute h-full right-0 flex items-center px-1 text-gray-500'>
        <RightOutlined onClick={onNext} />
      </div>
    </div>
  )
}

export default TimeWindowSelect

export * from './types'
export * from './SelectController'
