import { h } from 'preact'
import { useState, useEffect } from 'preact/hooks'
import { isWithinInterval, subHours } from 'date-fns'
import { zonedTimeToUtc, utcToZonedTime, format } from 'date-fns-tz'
import { addHours } from 'date-fns/esm'

import Video from './src/components/Video'
import config from './src/data/config'
import Info from './src/components/Info'
import { useEventStream } from './src/hooks/data'
import { useTimeout } from './src/hooks/timerHooks'

export default () => {
  const [currentVideo, setCurrentVideo] = useState(null)
  const [streamIsLive, setStreamIsLive] = useState(false)
  const [infoActive, setInfoActive] = useState(false)
  const [minLoadTimePassed, setMinTimeUp] = useState(false)
  const { data, loading } = useEventStream()

  useTimeout(() => {
    setMinTimeUp(true)
  }, 1500)

  useEffect(() => {
    if (data && data.length) {
      data.forEach((stream, index) => {
        const utcStartDate = zonedTimeToUtc(
          new Date(stream.start),
          'Europe/Berlin'
        )
        const utcEndDate = zonedTimeToUtc(new Date(stream.end), 'Europe/Berlin')
        const { timeZone } = Intl.DateTimeFormat().resolvedOptions()

        const zonedStartDate = utcToZonedTime(utcStartDate, timeZone)
        const zonedEndDate = utcToZonedTime(utcEndDate, timeZone)
        if (
          isWithinInterval(new Date(), {
            start: subHours(zonedStartDate, 1),
            end: addHours(zonedEndDate, 1),
          })
        ) {
          setCurrentVideo(stream)
        }
        if (
          isWithinInterval(new Date(), {
            start: zonedStartDate,
            end: zonedEndDate,
          })
        ) {
          setStreamIsLive(true)
        }
      })
    }
  }, [data])

  return (
    <div>
      {currentVideo && !infoActive && minLoadTimePassed ? (
        <Video video={currentVideo} setInfoActive={setInfoActive} />
      ) : (
        <Info
          data={data}
          loading={loading || !minLoadTimePassed}
          infoActive={infoActive}
          // infoActive
          currentVideo={currentVideo}
          setInfoActive={setInfoActive}
        />
      )}
    </div>
  )
}
