import { useRecoilValue } from 'recoil'

import { format } from 'date-fns'

import { T9n } from 'features/T9n'
import { Checkbox } from 'features/Common/Checkbox'
import { SportIcon } from 'features/SportIcon'
import { ArrowLoader } from 'features/ArrowLoader'

import { isMobileDevice } from 'config/userAgent'

import { dateForIos } from 'helpers/dateForIos'

import { MatchType, fetchingMatches } from '../../storeHighlightsAtoms'

import { useHighlighMatches } from './hooks'

import {
  ScTitle,
  ScMatchesWrapper,
  ScMatchesList,
  ScLabel,
  ScDate,
  ScTournament,
  ScTournamentName,
  ScCountryFlag,
  ScFakeDate,
  ScFakeTournamentName,
  ScFakeTournament,
  ScFakeCheckbox,
  ScFakeWrapper,
  ScCountMatches,
  ScLoaderWrapper,
} from './styled'

export const MatchesHighlights = () => {
  const {
    onChangeSelectedMatches,
    playerMatches,
  } = useHighlighMatches()

  const isFetching = useRecoilValue(fetchingMatches)

  return (
    <ScMatchesWrapper>
      <ScTitle>
        <T9n t='matches_highlight' />
        <ScCountMatches>
          {isMobileDevice ? ` (${playerMatches.length})` : ''}
        </ScCountMatches>
      </ScTitle>
      <ScMatchesList>
        {playerMatches.length ? (playerMatches?.map(({
          country_id,
          date,
          id,
          isChecked,
          sport,
          team1,
          team2,
          tournament,
        }: MatchType) => (
          <Checkbox
            key={id}
            id={id.toString()}
            checked={isChecked}
            onChange={onChangeSelectedMatches}
            className='matchesHighlights__Checkbox'
            label={(
              <ScLabel>
                <ScDate>
                  {format(new Date(dateForIos(date)), 'd MMM yyyy H:mm')}
                </ScDate>&nbsp;
                {team1.name_eng} - {team2.name_eng}
                <ScTournament>
                  <SportIcon sport={sport} />
                  <ScCountryFlag
                    src={`https://cf-aws.insports.tv/media/flags/${country_id}.png`}
                  />
                  <ScTournamentName>{tournament.name_eng}</ScTournamentName>
                </ScTournament>
              </ScLabel>
            )}
          />
        ))) : (Array.from(Array(12)).map(() => (
          <ScFakeWrapper key={Math.random()}>
            <ScFakeCheckbox className='skeleton' />
            <ScFakeTournament>
              <ScFakeDate className='skeleton' />
              <ScFakeTournamentName className='skeleton' />
            </ScFakeTournament>
          </ScFakeWrapper>
        )))}
        {isFetching ? (
          <ScLoaderWrapper>
            <ArrowLoader />
          </ScLoaderWrapper>
        ) : '' }
      </ScMatchesList>
    </ScMatchesWrapper>
  )
}
