import { Fragment, useMemo } from 'react'

import type { MediaPlaylist } from 'hls.js'

import map from 'lodash/map'

import { OutsideClick } from 'features/OutsideClick'

import { useToggle } from 'hooks'

import { isMobileDevice } from 'config/userAgent'

import {
  AudioTrackItem,
  AudioTrackItemText,
  AudioTracksWrapper,
  ScHeader,
  ScModal,
  SelectedAudioTrack,
  IconArrow,
} from './styled'

export type AudioTracksProps = {
  audioTracks: Array<MediaPlaylist>,
  changeAudioTrack: (trackId: number) => void,
  isFullscreen?: boolean,
  selectedAudioTrack: MediaPlaylist,
}

export const AudioTracks = ({
  audioTracks,
  changeAudioTrack,
  isFullscreen,
  selectedAudioTrack,
}: AudioTracksProps) => {
  const {
    close,
    isOpen,
    open,
  } = useToggle()

  const AudioTracksList = useMemo(() => (
    map(audioTracks, (track) => (
      <AudioTrackItem
        key={`${track.id}_${track.name}`}
        isFullScreen={Boolean(isFullscreen)}
        selected={track.id === selectedAudioTrack?.id}
        onClick={() => {
          changeAudioTrack(track.id)
          close()
        }}
      >
        <AudioTrackItemText>
          {track.name}
        </AudioTrackItemText>
      </AudioTrackItem>
    ))
  ), [
    audioTracks,
    changeAudioTrack,
    close,
    isFullscreen,
    selectedAudioTrack?.id,
  ])

  const content = isMobileDevice && !isFullscreen
    ? (
      <ScModal
        closeSize={12}
        close={close}
        isOpen={isOpen}
      >
        <ScHeader>Audio</ScHeader>
        {AudioTracksList}
      </ScModal>
    )
    : (
      <Fragment>
        {isOpen && (
          <AudioTracksWrapper>
            <OutsideClick onClick={close}>
              {AudioTracksList}
            </OutsideClick>
          </AudioTracksWrapper>
        )}
      </Fragment>
    )

  return (
    <Fragment>
      {audioTracks?.length > 1 && (
        <Fragment>
          <SelectedAudioTrack onClick={open}>
            {!selectedAudioTrack && audioTracks[0].name}
            {selectedAudioTrack?.name}
            <IconArrow active={isOpen} />
          </SelectedAudioTrack>
        </Fragment>
      )}
      {content}
    </Fragment>
  )
}
