import {
  useCallback,
  useMemo,
  useState,
} from 'react'

import map from 'lodash/map'
import groupBy from 'lodash/groupBy'
import reverse from 'lodash/reverse'
import filter from 'lodash/filter'
import values from 'lodash/values'
import flatten from 'lodash/flatten'
import { Events, MatchInfo } from 'requests'
import { useToggle } from 'hooks'
import { EventPlaylistOption } from 'features/MatchPage/types'

type TPropsTabEvents = {
  events?: Events,
  profile?: MatchInfo,
}

export const useTabEvents = ({
  events,
  profile,
}: TPropsTabEvents) => {
  const [likesOnly, setLikesOnly] = useState(false)

  const {
    close: setUnreversed,
    isOpen: areEventsReversed,
    open: setReversed,
  } = useToggle()

  const likeToggle = useCallback(() => setLikesOnly((state) => !state), [])
  const likeImage = likesOnly ? '/images/like-active-icon.svg' : '/images/likeDisable.svg'

  const isLiveMatch = profile?.live
  const reverseStatus = (areEventsReversed || isLiveMatch) && (areEventsReversed !== isLiveMatch)
  const activeStatus = isLiveMatch ? areEventsReversed : !areEventsReversed

  const reversedGroupEvents = useMemo(() => {
    const eventsList = likesOnly ? filter(events, 'like') : events
    const groupedEvents = values(
      groupBy(
        reverseStatus
          ? reverse([...eventsList!])
          : eventsList,
        ({ h }) => h,
      ),
    )
    return reverseStatus
      ? reverse(groupedEvents)
      : groupedEvents
  }, [
    events,
    likesOnly,
    reverseStatus,
  ])

  const episodesToPlay = map(flatten(reversedGroupEvents), ((event) => ({
    episodes: [{
      e: event.e,
      h: event.h,
      s: event.s,
    }],
    id: event.n,
    type: 3,
  }))) as Array<EventPlaylistOption>

  return {
    activeStatus,
    episodesToPlay,
    isLiveMatch,
    likeImage,
    likeToggle,
    reversedGroupEvents,
    setReversed,
    setUnreversed,
  }
}
