import map from 'lodash/map'

import type { Events, MatchInfo } from 'requests'

import { isLffClient } from 'config/clients'

import { T9n } from 'features/T9n'
import type {
  EventPlaylistOption,
  PlaylistOption,
} from 'features/MatchPage/types'
import { PlaylistTypes } from 'features/MatchPage/types'

import { isEqual } from '../../helpers'
import { EventButton } from '../EventButton'
import {
  BlockTitle,
  Event,
  TextEvent,
  List,
} from '../TabEvents/styled'

type Props = {
  disablePlayingEpisodes?: () => void,
  events: Events,
  onSelect: (option: PlaylistOption) => void,
  profile: MatchInfo,
  selectedPlaylist?: PlaylistOption,
  setWatchAllEpisodesTimer: (showTimer: boolean) => void,
}

export const EventsList = ({
  disablePlayingEpisodes,
  events,
  onSelect,
  profile,
  selectedPlaylist,
  setWatchAllEpisodesTimer,
}: Props) => (
  <List>
    {map(events, (event) => {
      if (!event.t && !event.pl) {
        return (
          <TextEvent key={event.n}>
            <BlockTitle>
              <T9n t={event.l} />
            </BlockTitle>
          </TextEvent>
        )
      }

      const repeatedEpisodes = event.rep || []
      const eventPlaylist = {
        episodes: [{
          e: event.e,
          h: event.h,
          s: event.s,
        },
        ...repeatedEpisodes,
        ],
        id: event.n,
        type: PlaylistTypes.EVENT,
      } as EventPlaylistOption

      const isHomeTeam = event.t === profile?.team1.id
      const team = isHomeTeam
        ? profile?.team1
        : profile?.team2
      const eventWithoutClick = isLffClient && profile?.live

      const eventClick = () => {
        setWatchAllEpisodesTimer(false)
        !eventWithoutClick && onSelect(eventPlaylist)
        if (disablePlayingEpisodes) {
          disablePlayingEpisodes()
        }
      }

      return (
        <Event key={event.n}>
          <EventButton
            active={isEqual(eventPlaylist, selectedPlaylist)}
            event={event}
            isHomeTeam={isHomeTeam}
            onClick={eventClick}
            team={team}
          />
        </Event>
      )
    })}
  </List>
)
