import { Fragment, useRef } from 'react'

import isNumber from 'lodash/isNumber'

import { KEYBOARD_KEYS } from 'config'

import type { Param, TeamStatItem } from 'requests'
import { getStatsEvents } from 'requests'

import { usePageParams, useEventListener } from 'hooks'

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

import { StatsType } from '../TabStats/config'
import { CircleAnimationBar } from '../CircleAnimationBar'

import {
  CellContainer,
  ParamValueContainer,
  ParamValue,
  Divider,
} from './styled'

type CellProps = {
  teamId: number,
  teamStatItem: TeamStatItem | null,
}

export const Cell = ({
  teamId,
  teamStatItem,
}: CellProps) => {
  const paramValueContainerRef = useRef(null)

  const { profileId, sportType } = usePageParams()

  const {
    playingData,
    playingProgress,
    playStatsEpisodes,
    profile,
    setIsPlayingFiltersEpisodes,
    setPlayingData,
    setWatchAllEpisodesTimer,
    statsType,
    watchAllEpisodesTimer,
  } = useMatchPageStore()

  const isClickable = (param: Param) => (
    Boolean(param.val) && param.clickable
  )

  const getDisplayedValue = (val: number | null) => (
    isNumber(val) ? String(val) : '-'
  )

  const onParamClick = async (param: Param) => {
    if (!isClickable(param)) return

    setWatchAllEpisodesTimer(false)
    setIsPlayingFiltersEpisodes(false)

    setPlayingData({
      player: {
        id: null,
        paramId: null,
      },
      team: {
        id: teamId,
        paramId: param.id,
      },
    })

    try {
      const events = await getStatsEvents({
        matchId: profileId,
        paramId: param.id,
        sportType,
        teamId,
        ...(statsType === StatsType.CURRENT_STATS && profile?.video_bounds && (
          getHalfTime(profile.video_bounds, playingProgress)
        )),
      })

      playStatsEpisodes(events)
    // eslint-disable-next-line no-empty
    } catch (e) {}
  }

  useEventListener({
    callback: (e) => {
      if (e.key !== KEYBOARD_KEYS.Enter || !teamStatItem) return

      const paramId = Number((e.target as HTMLElement).dataset.paramId)

      const param = paramId && (teamStatItem.param1.id === paramId
        ? teamStatItem.param1
        : teamStatItem.param2)

      param && onParamClick(param)
    },
    event: 'keydown',
    target: paramValueContainerRef,
  })

  if (!teamStatItem) return null

  return (
    <CellContainer>
      <ParamValueContainer ref={paramValueContainerRef}>
        {watchAllEpisodesTimer
          && playingData.team.paramId === teamStatItem.param1.id
          && playingData.team.id === teamId
          ? (
            <ParamValue>
              <CircleAnimationBar
                text={getDisplayedValue(teamStatItem.param1.val)}
                size={20}
              />
            </ParamValue>
          )
          : (
            <ParamValue
              clickable={isClickable(teamStatItem.param1)}
              onClick={() => onParamClick(teamStatItem.param1)}
              data-param-id={teamStatItem.param1.id}
            >
              {getDisplayedValue(teamStatItem.param1.val)}
            </ParamValue>
          )}

        {teamStatItem.param2 && (
          <Fragment>
            {watchAllEpisodesTimer
              && playingData.team.paramId === teamStatItem.param2.id
              && playingData.team.id === teamId
              ? (
                <ParamValue>
                  <CircleAnimationBar
                    text={getDisplayedValue(teamStatItem.param2.val)}
                    size={20}
                  />
                </ParamValue>
              )
              : (
                <Fragment>
                  <Divider>/</Divider>
                  <ParamValue
                    clickable={isClickable(teamStatItem.param2)}
                    onClick={() => onParamClick(teamStatItem.param2!)}
                    data-param-id={teamStatItem.param2.id}
                  >
                    {getDisplayedValue(teamStatItem.param2.val)}
                  </ParamValue>
                </Fragment>
              )}
          </Fragment>
        )}
      </ParamValueContainer>
    </CellContainer>
  )
}
