import React, {
  useState,
  useEffect,
  useCallback,
} from 'react'

import styled from 'styled-components/macro'
import differenceInMilliseconds from 'date-fns/differenceInMilliseconds'

import type { Match } from 'features/Matches'
import { getSportColor, msToMinutesAndSeconds } from 'helpers'
import { SportName } from 'features/Common'
import { T9n } from 'features/T9n'

import { useCard } from '../hooks'
import {
  CardWrapper,
  Info,
  MatchStatus as CommonMatchStatus,
  Preview,
  PreviewWrapper,
  Score,
  Team,
  TeamName,
  Teams,
  TournamentName,
} from '../styled'
import { CardLiveHover } from '../CardLiveHover'

const UPDATE_INTERVAL = 1000

const MatchStatus = styled(CommonMatchStatus)`
  color: #fff;
  background-color: #cc0000;
`

type CardLiveProps = {
  match: Match,
}

export const CardLive = ({
  match: {
    date,
    id,
    preview,
    sportName,
    sportType,
    team1Name,
    team1Score,
    team2Name,
    team2Score,
    tournamentName,
  },
}: CardLiveProps) => {
  const {
    close,
    isOpen,
    onKeyPress,
    open,
    showScore,
  } = useCard()

  const getMs = useCallback(() => differenceInMilliseconds(
    new Date(),
    new Date(date),
  ), [date])

  const [matchDuration, setMatchDuration] = useState(msToMinutesAndSeconds(getMs()))

  useEffect(() => {
    const timer = setInterval(() => {
      setMatchDuration(msToMinutesAndSeconds(getMs()))
    }, UPDATE_INTERVAL)

    return () => clearInterval(timer)
  }, [getMs])

  if (isOpen) return <CardLiveHover onClose={close} />

  return (
    <CardWrapper
      onClick={open}
      onKeyPress={onKeyPress}
    >
      <MatchStatus><T9n t='live' /> {matchDuration}</MatchStatus>
      <PreviewWrapper>
        <Preview
          alt={tournamentName}
          title={tournamentName}
          src={preview}
        />
      </PreviewWrapper>
      <Info>
        <SportName t={sportName} color={getSportColor(sportType)} />
        <TournamentName title={tournamentName}>{tournamentName}</TournamentName>
        <Teams>
          <Team>
            <TeamName title={team1Name}>{team1Name}</TeamName>
            {showScore && <Score>{team1Score}</Score>}
          </Team>
          <Team>
            <TeamName title={team2Name}>{team2Name}</TeamName>
            {showScore && <Score>{team2Score}</Score>}
          </Team>
        </Teams>
      </Info>
    </CardWrapper>
  )
}
