import type { KeyboardEvent } from 'react'
import { useLocation, useRouteMatch } from 'react-router'

import getUnixTime from 'date-fns/getUnixTime'

import { ProfileTypes, PAGES } from 'config'
import { client } from 'config/clients'

import type { LiveScore } from 'requests'

import type { Match } from 'features/Matches'
import { useMatchSwitchesStore } from 'features/MatchSwitches'
import { useName } from 'features/Name'
import { T9n } from 'features/T9n'
import { MatchAccess } from 'features/Matches/helpers/getMatchClickAction'
import { useUserFavoritesStore } from 'features/UserFavorites/store'
import { TournamentSubtitle } from 'features/TournamentSubtitle'
import { useHeaderFiltersStore } from 'features/HeaderFilters'
import { NoAccessMessage } from '../NoAccessMessage'
import { Score } from '../Score'
import {
  CardWrapperOuter,
  CardWrapper,
  Info,
  LiveSign,
  MatchDate,
  MatchTimeInfo,
  Preview,
  PreviewWrapper,
  Team,
  TeamName,
  Teams,
  Time,
  TeamLogos,
  TeamLogo,
  BuyMatchBadge,
  BuyMatchBadgeCustom,
  FavoriteSign,
  NameSignWrapper,
  HoverFrame,
} from '../styled'
import { useCardPreview } from './hooks'
import { getPrepareTimeFormat } from '../helpers'
import { getPrepareDateFormat } from '../helpers/getPrepareDateFormat'
import { Icon } from '../../Icon'

type Props = {
  isNeedFormatTimeChanged: boolean,
  match: Match,
  onClick: () => void,
  onKeyPress: (e: KeyboardEvent<HTMLLIElement>) => void,
  score?: LiveScore,
}

export const CardFrontside = ({
  isNeedFormatTimeChanged,
  match,
  onClick,
  onKeyPress,
  score,
}: Props) => {
  const location = useLocation()
  const {
    access,
    countryId,
    countryInfo,
    date,
    group,
    live,
    preview,
    previewURL,
    sportInfo,
    sportType,
    team1,
    team2,
    time,
    tournament,
  } = match

  const isHomePage = useRouteMatch(PAGES.home)?.isExact
  const isMatchPage = location.pathname.includes(PAGES.match)
  const tournamentName = useName(tournament)
  const { isInFavorites } = useUserFavoritesStore()
  const { isScoreHidden } = useMatchSwitchesStore()
  const { isMonthMode } = useHeaderFiltersStore()
  const { color } = tournament
  const isInFuture = getUnixTime(date) > getUnixTime(new Date())
  const showScore = !(
    isInFuture
    || isScoreHidden
  ) || (live && !isScoreHidden)
  const team1InFavorites = isInFavorites(ProfileTypes.TEAMS, team1.id)
  const team2InFavorites = isInFavorites(ProfileTypes.TEAMS, team2.id)

  const { previewImage } = useCardPreview({
    preview,
    previewURL,
  })

  const prepareTime = getPrepareTimeFormat({
    date,
    isNeedFormatTimeChanged,
    time,
  })

  const prepareDate = getPrepareDateFormat({
    date,
    isNeedFormatTimeChanged,
  })

  return (
    <CardWrapperOuter
      onClick={onClick}
      onKeyPress={onKeyPress}
      isMatchPage={isMatchPage}
    >
      <CardWrapper
        isMatchPage={isMatchPage}
        gradientColor={color || group?.color}
      >
        <HoverFrame />
        <PreviewWrapper isMatchPage={isMatchPage}>
          {previewImage && (
            <Preview
              isMatchPage={isMatchPage}
              title={tournamentName}
              src={previewImage}
            />
          )}
          {access === MatchAccess.NoCountryAccess
            ? <NoAccessMessage />
            : (
              <TeamLogos isMatchPage={isMatchPage}>
                <TeamLogo
                  id={team1.id}
                  logoUrl={team1.media?.logo_url}
                  nameAsTitle
                  altNameObj={team1}
                  sportType={sportType}
                  profileType={ProfileTypes.TEAMS}
                />
                <TeamLogo
                  id={team2.id}
                  logoUrl={team2.media?.logo_url}
                  nameAsTitle
                  altNameObj={team2}
                  sportType={sportType}
                  profileType={ProfileTypes.TEAMS}
                />
              </TeamLogos>
            )}
          {access === MatchAccess.CanBuyMatch && !isMatchPage && (
            <BuyMatchBadge>
              <Icon
                styles={{
                  display: 'flex',
                  justifyContent: 'center',
                }}
                refIcon={client.currencyBadge.sign}
                size='0.85rem'
                color={client.currencyBadge.color}
              />
            </BuyMatchBadge>
          )}
          <MatchTimeInfo isMatchPage={isMatchPage}>
            {access === MatchAccess.CanBuyMatch && isMatchPage && (
              <BuyMatchBadgeCustom>
                <Icon
                  styles={{
                    display: 'flex',
                    justifyContent: 'center',
                  }}
                  refIcon={client.currencyBadge.sign}
                  size={13}
                  color={client.currencyBadge.secondColor}
                />
              </BuyMatchBadgeCustom>
            )}
            <MatchDate
              isHomePage={isHomePage}
              isMatchPage={isMatchPage}
              isMonthMode={isMonthMode}
            >
              {(isHomePage && !isMonthMode) || isMatchPage ? null : prepareDate}
              <Time>{prepareTime}</Time>
            </MatchDate>
            {live && (
              <LiveSign isMatchPage={isMatchPage}>
                <T9n t='live' />
              </LiveSign>
            )}
          </MatchTimeInfo>
        </PreviewWrapper>
        <Info isMatchPage={isMatchPage}>
          <Teams isMatchPage={isMatchPage}>
            <Team isMatchPage={isMatchPage}>
              <NameSignWrapper>
                {isMatchPage && (
                  <TeamLogo
                    isMatchPage
                    id={team1.id}
                    logoUrl={team1.media?.logo_url}
                    nameAsTitle
                    altNameObj={team1}
                    sportType={sportType}
                    profileType={ProfileTypes.TEAMS}
                  />
                )}
                <TeamName nameObj={team1} />
                {team1InFavorites && <FavoriteSign />}
              </NameSignWrapper>
              <Score
                showScore={showScore}
                score={score?.team1.score ?? team1.score}
                penaltyScore={score?.team1.penalty_score ?? team1.penalty_score}
              />
            </Team>
            <Team isMatchPage={isMatchPage}>
              <NameSignWrapper>
                {isMatchPage && (
                  <TeamLogo
                    isMatchPage
                    id={team2.id}
                    logoUrl={team2.media?.logo_url}
                    nameAsTitle
                    altNameObj={team2}
                    sportType={sportType}
                    profileType={ProfileTypes.TEAMS}
                  />
                )}
                <TeamName nameObj={team2} />
                {team2InFavorites && <FavoriteSign />}
              </NameSignWrapper>
              <Score
                showScore={showScore}
                score={score?.team2.score ?? team2.score}
                penaltyScore={score?.team2.penalty_score ?? team2.penalty_score}
              />
            </Team>
          </Teams>
          {!isMatchPage && (
            <TournamentSubtitle
              countryId={countryId}
              countryInfo={countryInfo}
              sportInfo={sportInfo}
              sportType={sportType}
              tournament={tournament.is_super_tournament ? group : tournament}
            />
          )}
        </Info>
      </CardWrapper>
    </CardWrapperOuter>
  )
}
