import { useCallback, useEffect, useRef, useState } from 'react'

type SeekDirection = 'forward' | 'backward'

export interface SeekIndicatorState {
  direction: SeekDirection
  key: number
}

export function usePlayerChrome(isPaused: boolean) {
  const [controlsVisible, setControlsVisible] = useState(true)
  const [seekIndicator, setSeekIndicator] = useState<SeekIndicatorState | null>(null)
  const [transientToast, setTransientToast] = useState<string | null>(null)
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null)

  const showControls = useCallback(() => {
    setControlsVisible(true)
    if (hideTimer.current) clearTimeout(hideTimer.current)
    hideTimer.current = setTimeout(() => {
      if (!isPaused) setControlsVisible(false)
    }, 2500)
  }, [isPaused])

  useEffect(() => {
    if (isPaused) {
      setControlsVisible(true)
      if (hideTimer.current) clearTimeout(hideTimer.current)
    } else {
      showControls()
    }
  }, [isPaused, showControls])

  useEffect(() => () => {
    if (hideTimer.current) clearTimeout(hideTimer.current)
  }, [])

  function showSeekIndicator(direction: SeekDirection) {
    setSeekIndicator({ direction, key: Date.now() })
  }

  function showToast(msg: string) {
    setTransientToast(msg)
    setTimeout(() => setTransientToast(null), 1600)
  }

  return {
    controlsVisible,
    seekIndicator,
    transientToast,
    showControls,
    showSeekIndicator,
    showToast,
  }
}
