import type { Dispatch, SetStateAction } from 'react'
import { useEffect } from 'react'

import isEmpty from 'lodash/isEmpty'
import size from 'lodash/size'

import { useMatchPageStore } from 'features/MatchPage/store'

import { fullEpisodesDuration } from './helpers'
import { Svg, Circle } from './styled'

export type TCircleAnimation = {
  plaingOrder: number,
  playedProgress: number,
  playing: boolean,
  ready: boolean,
}

export const initialCircleAnimation: TCircleAnimation = {
  plaingOrder: 0,
  playedProgress: 0,
  playing: false,
  ready: false,
}

type Props = {
  className?: string,
  size?: number,
  text?: string,
}

export type TSetCircleAnimation = Dispatch<SetStateAction<TCircleAnimation>>

export const CircleAnimationBar = ({
  className,
  size: svgSize = 14,
  text,
}: Props) => {
  const {
    circleAnimation,
    filteredEvents,
    setWatchAllEpisodesTimer,
  } = useMatchPageStore()

  const {
    plaingOrder,
    playedProgress,
    playing,
    ready,
  } = circleAnimation

  const timeOfAllEpisodes = fullEpisodesDuration(filteredEvents)
  const remainingEvents = filteredEvents.slice(plaingOrder && plaingOrder - 1)
  const fullTimeOfRemainingEpisodes = !isEmpty(remainingEvents)
    ? fullEpisodesDuration(remainingEvents)
    : 0
  const animationPause = !playing || !ready

  const currentAnimationTime = Math.round(fullTimeOfRemainingEpisodes - (playedProgress / 1000))
  const currentEpisodesPercent = 100 - (100 / (timeOfAllEpisodes / currentAnimationTime))

  const strokeDashOffset = svgSize * Math.PI

  useEffect(() => {
    if (currentEpisodesPercent >= 100 && (plaingOrder === size(filteredEvents))) {
      setWatchAllEpisodesTimer(false)
    }
  }, [
    currentEpisodesPercent,
    filteredEvents,
    plaingOrder,
    setWatchAllEpisodesTimer,
  ])

  return (
    <Svg
      className={className}
      size={svgSize}
    >
      <Circle
        cx='50%'
        cy='50%'
        r='50%'
        currentAnimationTime={currentAnimationTime}
        animationPause={animationPause}
        currentEpisodesPercent={currentEpisodesPercent}
        strokeDashOffset={strokeDashOffset}
      />
      {text && (
        <text
          x='50%'
          y='50%'
          dominantBaseline='middle'
          textAnchor='middle'
        >
          {text}
        </text>
      )}
    </Svg>
  )
}
