import { useCallback } from 'react'

import { useQuery } from 'react-query'

import { format } from 'date-fns'

import includes from 'lodash/includes'
import isNil from 'lodash/isNil'

import type { Team } from 'requests/getMatchInfo'

import { getName, Name } from 'features/Name'
import { useAuthStore } from 'features/AuthStore'
import { useMatchSwitchesStore } from 'features/MatchSwitches'
import { TournamentSubtitle } from 'features/TournamentSubtitle'
import { useLexicsStore } from 'features/LexicsStore'
import { useMatchPageStore } from 'features/MatchPage/store'

import { parseDate } from 'helpers/parseDate'

import {
  ProfileTypes,
  querieKeys,
  isMobileDevice,
} from 'config'

import { usePageParams } from 'hooks/usePageParams'

import { getMatchScore } from 'requests'

import {
  Description,
  DescriptionInnerBlock,
  MatchDate,
  Score,
  StyledLink,
  Time,
  Title,
  Views,
} from './styled'

export const MatchDescription = () => {
  const {
    profileId,
    sportType,
  } = usePageParams()
  const { user } = useAuthStore()
  const { isScoreHidden } = useMatchSwitchesStore()
  const { suffix } = useLexicsStore()
  const { profile, profileCardShown } = useMatchPageStore()

  const getTeamName = useCallback((team: Team) => (
    isMobileDevice
      ? getName({ nameObj: team, suffix })
      : <Name nameObj={team} />
  ), [suffix])

  const { data: queryScore } = useQuery({
    queryFn: async () => {
      if (profile?.live && !isScoreHidden) {
        const score = await getMatchScore({ profileId, sportType })
        return score
      }

      return null
    },
    queryKey: querieKeys.matchScore,
    refetchInterval: 5000,
  })

  if (!profile) return <Description />

  const {
    country,
    country_id,
    date,
    sport,
    team1,
    team2,
    tournament,
  } = profile

  const isChangedTimeFormat = includes(['US', 'CA'], user?.profile.country_code)
  const localDate = format(parseDate(date), isMobileDevice ? 'MMM d, y' : 'MMMM d, y')
  const changedTimeFormat = format(parseDate(date),
    isChangedTimeFormat ? 'h:mm a' : 'HH:mm')

  return (
    <Description isHidden={!profileCardShown}>
      <DescriptionInnerBlock>
        <Title>
          <StyledLink
            id={team1.id}
            profileType={ProfileTypes.TEAMS}
            sportType={sportType}
          >
            {getTeamName(team1)}
          </StyledLink>
          <Score>
            {
              isScoreHidden || isNil(team1.score) || isNil(team2.score)
                ? '-'
                : `${queryScore?.team1.score ?? team1.score} - ${queryScore?.team2.score ?? team2.score}`

            }
          </Score>
          <StyledLink
            id={team2.id}
            profileType={ProfileTypes.TEAMS}
            sportType={sportType}
          >
            {getTeamName(team2)}
          </StyledLink>
        </Title>
        <TournamentSubtitle
          countryInfo={country}
          countryId={country_id}
          sportInfo={sport}
          tournament={tournament}
          time={isMobileDevice ? changedTimeFormat : null}
          date={isMobileDevice ? localDate : null}
        />
      </DescriptionInnerBlock>
      {
        !isMobileDevice && (
          <Views>
            <Time>{changedTimeFormat}</Time>
            <MatchDate>{localDate}</MatchDate>
          </Views>
        )
      }
    </Description>
  )
}
