import { useMemo, useCallback } from 'react'

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

import type { Player } 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 getPlayerName = useCallback((player: Player) => (
    trim(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, 'ord')
      : orderBy(
        players,
        [
          (player) => {
            const paramValue = getParamValue(player.id, sortCondition.paramId!)

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

  return {
    getPlayerName,
    getPlayerParams,
    isExpanded,
    players: sortedPlayers,
    toggleIsExpanded,
  }
}
