import { useEffect } from 'react'

import { useQuery } from 'react-query'

import map from 'lodash/map'
import isEmpty from 'lodash/isEmpty'

import type { Match } from 'helpers'

import { querieKeys } from 'config'

import { MatchCard } from 'features/MatchCard'
import { useMatchSwitchesStore } from 'features/MatchSwitches'

import { LiveScore, getLiveScores } from 'requests'

import { useMatchesSlider } from './hooks'
import {
  Wrapper,
  Arrow,
  Slides,
  ArrowButton,
} from './styled'

type MatchesSliderProps = {
  matches: Array<Match>,
}

export const MatchesSlider = ({ matches }: MatchesSliderProps) => {
  const {
    isLeftArrowDisabled,
    isRightArrowDisabled,
    onScroll,
    onWrapperMouseEnter,
    onWrapperMouseLeave,
    showLeftArrow,
    showRightArrow,
    slideLeft,
    slideRight,
    slidesRef,
  } = useMatchesSlider(matches)

  const { isScoreHidden } = useMatchSwitchesStore()

  const { data: liveMatchScores } = useQuery({
    queryFn: async () => {
      if (!isScoreHidden && matches.filter(({ live }) => live)?.length > 0) {
        const scores = await getLiveScores()
        return scores
      }
      return []
    },
    queryKey: querieKeys.liveMatchScores,
    refetchInterval: 5000,
  })

  const scrollToMatchByIndex = (index: number) => {
    const offsetLeftCount = slidesRef.current!.querySelectorAll('li')[index].offsetLeft
    const PADDING_PARENT = 10

    const offsetLeft = offsetLeftCount - PADDING_PARENT

    slidesRef.current!.scrollBy(offsetLeft, 0)
  }

  // скролл к лайв матчам или сегодняшней дате
  useEffect(() => {
    const matchIndexLive = matches.findIndex(({ live }) => live)
    if (matchIndexLive !== -1) {
      scrollToMatchByIndex(matchIndexLive)
      return
    }

    const matchIndex = matches.findIndex((item) => new Date() <= item.date)
    if (matchIndex !== -1) {
      scrollToMatchByIndex(matchIndex)
      return
    }

    const slidesRefClientWidth = slidesRef.current!.clientWidth
    const slidesRefScrollWidth = slidesRef.current!.scrollWidth
    slidesRef.current!.scrollBy(slidesRefScrollWidth - slidesRefClientWidth, 0)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  if (isEmpty(matches)) return null

  return (
    <Wrapper
      onMouseEnter={onWrapperMouseEnter}
      onMouseLeave={onWrapperMouseLeave}
    >
      {showLeftArrow && (
        <ArrowButton
          direction='left'
          onClick={slideLeft}
          disabled={isLeftArrowDisabled}
        >
          <Arrow
            disabled={isLeftArrowDisabled}
            direction='left'
          />
        </ArrowButton>
      )}
      <Slides ref={slidesRef} onScroll={onScroll}>
        {map(matches, (match) => (
          <MatchCard
            match={match}
            key={match.id}
            score={liveMatchScores?.find(
              ({ match_id, sport_id }: LiveScore) => match_id === match.id
              && sport_id === match.sportType,
            )}
          />
        ))}
      </Slides>
      {showRightArrow && (
        <ArrowButton
          direction='right'
          onClick={slideRight}
          disabled={isRightArrowDisabled}
        >
          <Arrow
            disabled={isRightArrowDisabled}
            direction='right'
          />
        </ArrowButton>
      )}
    </Wrapper>
  )
}
