import { useMemo, useCallback } from 'react'

import orderBy from 'lodash/orderBy'
import isNil from 'lodash/isNil'
import trim from 'lodash/trim'

import type { Player, PlayerParam } from 'requests'

import { useToggle } from 'hooks'

import { useMatchPageStore } from 'features/MatchPage/store'
import { useLexicsStore } from 'features/LexicsStore'

import type { SortCondition } from '../types'

type UsePlayersArgs = {
  sortCondition: SortCondition,
  teamId: number,
}

export const usePlayers = ({ sortCondition, teamId }: UsePlayersArgs) => {
  const { isOpen: isExpanded, toggle: toggleIsExpanded } = useToggle()
  const {
    playersData,
    playersStats,
    profile: matchProfile,
  } = useMatchPageStore()
  const { suffix } = useLexicsStore()

  const getPlayerParams = useCallback(
    (playerId: number) => playersStats[teamId][playerId] || {},
    [playersStats, teamId],
  )

  const getDisplayedValue = ({ val }: PlayerParam) => (isNil(val) ? '-' : val)

  const getFullName = useCallback((player: Player) => (
    trim(`${player[`firstname_${suffix}`]} ${player[`lastname_${suffix}`]}`)
  ), [suffix])

  const getParamValue = useCallback((playerId: number, paramId: number) => {
    const playerParams = getPlayerParams(playerId)
    const { val } = playerParams[paramId] || {}

    return val
  }, [getPlayerParams])

  const sortedPlayers = useMemo(() => {
    const players = playersData[matchProfile?.team1.id === teamId ? 'team1' : 'team2']

    return isNil(sortCondition.paramId)
      ? orderBy(players, getFullName)
      : orderBy(
        players,
        [
          (player) => {
            const paramValue = getParamValue(player.id, sortCondition.paramId!)

            return isNil(paramValue) ? -1 : paramValue
          },
          getFullName,
        ],
        sortCondition.dir,
      )
  }, [
    getFullName,
    getParamValue,
    playersData,
    matchProfile?.team1.id,
    sortCondition.dir,
    sortCondition.paramId,
    teamId,
  ])

  return {
    getDisplayedValue,
    getFullName,
    getPlayerParams,
    isExpanded,
    players: sortedPlayers,
    toggleIsExpanded,
  }
}
