import { useEffect, useState } from 'react'

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

import type { SortCondition, PlayersTableProps } from '../types'
import { usePlayers } from './usePlayers'
import { useTable } from './useTable'

export const usePlayersTable = ({ teamId }: PlayersTableProps) => {
  const [sortCondition, setSortCondition] = useState<SortCondition>({
    clicksCount: 0,
    dir: 'asc',
    paramId: null,
  })

  const { plaingOrder, setCircleAnimation } = useMatchPageStore()

  const {
    getPlayerName,
    getPlayerParams,
    players,
  } = usePlayers({ sortCondition, teamId })

  const {
    containerRef,
    getDisplayedValue,
    handleParamClick,
    handleScroll,
    handleSortClick,
    isExpanded,
    paramColumnWidth,
    params,
    showExpandButton,
    showLeftArrow,
    showRightArrow,
    slideLeft,
    slideRight,
    tableWrapperRef,
    toggleIsExpanded,
  } = useTable({
    setSortCondition,
    teamId,
  })

  useEffect(() => {
    setCircleAnimation((state) => ({
      ...state,
      plaingOrder,
    }))
  }, [setCircleAnimation, plaingOrder])

  return {
    containerRef,
    getDisplayedValue,
    getPlayerName,
    getPlayerParams,
    handleParamClick,
    handleScroll,
    handleSortClick,
    isExpanded,
    paramColumnWidth,
    params,
    players,
    showExpandButton,
    showLeftArrow,
    showRightArrow,
    slideLeft,
    slideRight,
    sortCondition,
    tableWrapperRef,
    toggleIsExpanded,
  }
}
