import type { SyntheticEvent } from 'react'
import {
  useEffect,
  useRef,
  useMemo,
  useState,
  useCallback,
} from 'react'

import throttle from 'lodash/throttle'

import type { Match } from 'features/Matches'
import { MATCH_CARD_WIDTH, MATCH_CARD_GAP } from 'features/MatchCard/config'

const MATCHES_TO_SCROLL = 6

const SCROLLING_DELAY = 750

export const useMatchesSlider = (matches: Array<Match>) => {
  const slidesRef = useRef<HTMLUListElement>(null)

  const [showLeftArrow, setShowLeftArrow] = useState(false)
  const [showRightArrow, setShowRigthArrow] = useState(false)

  useEffect(() => {
    const {
      clientWidth = 0,
      scrollLeft = 0,
      scrollWidth = 0,
    } = slidesRef.current || {}
    const scrollRight = scrollWidth - (scrollLeft + clientWidth)

    setShowRigthArrow(scrollRight > 1)
  }, [matches, slidesRef])

  const onScroll = useCallback((e: SyntheticEvent<HTMLUListElement>) => {
    const {
      clientWidth: targetClientWidth,
      scrollLeft: targetScrollLeft,
      scrollWidth: targetScrollWidth,
    } = e.currentTarget

    setShowLeftArrow(targetScrollLeft > 1)
    setShowRigthArrow((targetScrollWidth - (targetScrollLeft + targetClientWidth)) > 1)
  }, [])

  const slideLeft = useMemo(() => throttle(() => {
    slidesRef.current!.scrollBy(-((MATCH_CARD_WIDTH + MATCH_CARD_GAP) * MATCHES_TO_SCROLL), 0)
  }, SCROLLING_DELAY), [])

  const slideRight = useMemo(() => throttle(() => {
    slidesRef.current!.scrollBy((MATCH_CARD_WIDTH + MATCH_CARD_GAP) * MATCHES_TO_SCROLL, 0)
  }, SCROLLING_DELAY), [])

  return {
    onScroll,
    showLeftArrow,
    showRightArrow,
    slideLeft,
    slideRight,
    slidesRef,
  }
}
