import { useMemo } from 'react'

import map from 'lodash/map'
import flatten from 'lodash/flatten'
import pipe from 'lodash/fp/pipe'
import fpMap from 'lodash/fp/map'
import fpOrderBy from 'lodash/fp/orderBy'

import type { Matches, Content } from 'requests'
import { SPORT_NAMES } from 'config'
import { getProfileLogo } from 'helpers'
import { useLexicsStore } from 'features/LexicsStore'

export type Props = {
  matches: Matches,
}

type Name = 'name_rus' | 'name_eng'

export type Match = {
  date: string,
  id: number,
  preview: string,
  sportName: string,
  sportType: number,
  streamStatus: number,
  team1Logo: string,
  team1Name: string,
  team1Score: number,
  team2Logo: string,
  team2Name: string,
  team2Score: number,
  tournamentName: string,
}

const prepareMatches = (content: Array<Content>, suffix: string) => pipe(
  fpMap<Content, Array<Match>>(({
    matches: matchesList,
    sport,
    ...rest
  }) => map(matchesList, ({
    date,
    id,
    stream_status,
    team1,
    team2,
  }) => ({
    date,
    id,
    preview: '/images/preview.png',
    sportName: SPORT_NAMES[sport],
    sportType: sport,
    streamStatus: stream_status,
    team1Logo: getProfileLogo({
      id: team1.id,
      profileType: 2,
      sportType: sport,
    }),
    team1Name: team1[`name_${suffix}` as Name],
    team1Score: team1.score,
    team2Logo: getProfileLogo({
      id: team2.id,
      profileType: 2,
      sportType: sport,
    }),
    team2Name: team2[`name_${suffix}` as Name],
    team2Score: team2.score,
    tournamentName: rest[`name_${suffix}` as Name],
  }))),
  flatten,
  fpOrderBy((match: Match) => Number(new Date(match.date)), 'desc'),
)(content) as Array<Match>

export const useMatches = ({ matches }: Props) => {
  const { suffix } = useLexicsStore()

  return useMemo(() => ({
    broadcast: prepareMatches(matches.broadcast, suffix),
    features: prepareMatches(matches.features, suffix),
    highlights: prepareMatches(matches.highlights, suffix),
    isVideoSections: matches.isVideoSections,
  }), [suffix, matches])
}
