import {
  Fragment,
  useMemo,
  useRef,
} from 'react'

import size from 'lodash/size'
import filter from 'lodash/filter'

import type {
  PlaylistOption,
  Playlists,
  TournamentData,
} from 'features/MatchPage/types'
import type { MatchInfo } from 'requests'

import { DropdownSection } from '../DropdownSection'
import { MatchPlaylists, LIST_INDENT } from '../MatchPlaylists'
import { SideInterviews } from '../SideInterviews'
import { Matches } from '../Matches'

type Props = {
  onSelect: (option: PlaylistOption) => void,
  playlists: Playlists,
  profile: MatchInfo,
  selectedPlaylist?: PlaylistOption,
  tournamentData: TournamentData,
}

export const TabWatch = ({
  onSelect,
  playlists,
  profile,
  selectedPlaylist,
  tournamentData,
}: Props) => {
  const matchPlaylistsRef = useRef<HTMLUListElement>(null)

  const additionalScrollHeight = (matchPlaylistsRef.current?.clientHeight || 0) + LIST_INDENT

  const filteredPlayListByDuration = useMemo(() => (
    filter(playlists.match, (playlist) => (
      profile?.live
        ? Boolean(playlist.duration) || (playlist.id === 'full_game')
        : Boolean(playlist.duration)
    ))
  ), [playlists.match, profile?.live])

  return (
    <Fragment>
      <MatchPlaylists
        ref={matchPlaylistsRef}
        playlists={filteredPlayListByDuration}
        selectedMathPlaylist={selectedPlaylist}
        onSelect={onSelect}
        live={profile?.live}
      />
      <DropdownSection
        itemsCount={size(playlists.interview)}
        title={playlists.lexics?.interview}
      >
        <SideInterviews
          interviews={playlists.interview}
          selectedMathPlaylist={selectedPlaylist}
          onSelect={onSelect}
        />
      </DropdownSection>
      <Matches
        profile={profile}
        tournamentData={tournamentData}
        additionalScrollHeight={additionalScrollHeight}
      />
    </Fragment>
  )
}
