import { Fragment } from 'react'

import map from 'lodash/map'
import includes from 'lodash/includes'

import { PlayerParam } from 'requests'

import { usePageParams } from 'hooks'

import { useLexicsStore } from 'features/LexicsStore'
import { useMatchPageStore } from 'features/MatchPage/store'
import { Loader } from 'features/Loader'
import { defaultTheme } from 'features/Theme/config'

import type { PlayersTableProps } from './types'
import { FIRST_COLUMN_WIDTH_DEFAULT, FIRST_COLUMN_WIDTH_EXPANDED } from './config'
import { usePlayersTable } from './hooks'
import { Cell } from './Cell'
import {
  Container,
  TableWrapper,
  Table,
  Header,
  Row,
  PlayerNum,
  PlayerName,
  ParamShortTitle,
  ArrowButtonRight,
  ArrowButtonLeft,
  Arrow,
  ExpandButton,
} from './styled'
import { CircleAnimationBar } from '../CircleAnimationBar'

export const PlayersTable = (props: PlayersTableProps) => {
  const {
    containerRef,
    getDisplayedValue,
    getPlayerName,
    getPlayerParams,
    handleParamClick,
    handleScroll,
    handleSortClick,
    isExpanded,
    paramColumnWidth,
    params,
    players,
    showExpandButton,
    showLeftArrow,
    showRightArrow,
    slideLeft,
    slideRight,
    sortCondition,
    tableWrapperRef,
    toggleIsExpanded,
  } = usePlayersTable(props)
  const { translate } = useLexicsStore()
  const { sportName } = usePageParams()
  const {
    isPlayersStatsFetching,
    playingData,
    watchAllEpisodesTimer,
  } = useMatchPageStore()

  const firstColumnWidth = isExpanded ? FIRST_COLUMN_WIDTH_EXPANDED : FIRST_COLUMN_WIDTH_DEFAULT

  return (
    <Container
      ref={containerRef}
      isExpanded={isExpanded}
    >
      {isPlayersStatsFetching
        ? <Loader color={defaultTheme.colors.white} />
        : (
          <TableWrapper
            ref={tableWrapperRef}
            isExpanded={isExpanded}
            onScroll={handleScroll}
          >
            {!isExpanded && (
              <Fragment>
                {showRightArrow && (
                  <ArrowButtonRight
                    aria-label='Scroll to right'
                    onClick={slideRight}
                  >
                    <Arrow direction='right' />
                  </ArrowButtonRight>
                )}
              </Fragment>
            )}
            <Table role='marquee' aria-live='off'>
              <Header>
                <Row>
                  <Cell
                    as='th'
                    columnWidth={firstColumnWidth}
                  >
                    {showLeftArrow && (
                      <ArrowButtonLeft
                        aria-label='Scroll to left'
                        onClick={slideLeft}
                      >
                        <Arrow direction='left' />
                      </ArrowButtonLeft>
                    )}
                    {showExpandButton && (
                      <ExpandButton
                        isExpanded={isExpanded}
                        aria-label={isExpanded ? 'Reduce' : 'Expand'}
                        onClick={toggleIsExpanded}
                      >
                        <Arrow direction={isExpanded ? 'right' : 'left'} />
                        <Arrow direction={isExpanded ? 'right' : 'left'} />
                      </ExpandButton>
                    )}
                  </Cell>
                  {map(params, ({
                    id,
                    lexic,
                    lexica_short,
                  }) => (
                    <Cell
                      as='th'
                      key={id}
                      columnWidth={paramColumnWidth}
                      onClick={handleSortClick(id)}
                      sorted={sortCondition.paramId === id}
                      tooltipText={translate(lexic)}
                      anchorId={`param_${id}`}
                    >
                      <ParamShortTitle
                        id={`param_${id}`}
                        t={lexica_short || ''}
                        sorted={sortCondition.paramId === id}
                        sortDirection={sortCondition.dir}
                        showLeftArrow={showLeftArrow}
                      />
                    </Cell>
                  ))}
                </Row>
              </Header>

              <tbody>
                {map(players, (player) => {
                  const playerName = getPlayerName(player)
                  const playerNum = player.num ?? player.club_shirt_num
                  const playerProfileUrl = `/${sportName}/players/${player.id}`

                  return (
                    <Row key={player.id}>
                      <Cell columnWidth={firstColumnWidth}>
                        <PlayerNum>{playerNum}</PlayerNum>{' '}
                        <PlayerName to={playerProfileUrl}>
                          {playerName}
                        </PlayerName>
                      </Cell>
                      {map(params, (param) => {
                        const playerParam = getPlayerParams(player.id)[
                          param.id
                        ] as PlayerParam | undefined
                        const value = playerParam ? getDisplayedValue(playerParam) : '-'
                        // eslint-disable-next-line max-len
                        const clickable = Boolean(playerParam?.clickable) && !includes([0, '-'], value)
                        const sorted = sortCondition.paramId === param.id
                        const onClick = () => {
                          clickable && handleParamClick(param.id, player.id)
                        }

                        return (
                          <Cell
                            columnWidth={paramColumnWidth}
                            key={param.id}
                            clickable={clickable}
                            sorted={sorted}
                            onClick={onClick}
                          >
                            {watchAllEpisodesTimer
                              && param.id === playingData.player.paramId
                              && player.id === playingData.player.id
                              ? (
                                <CircleAnimationBar
                                  text={value}
                                  size={20}
                                />
                              )
                              : value}
                          </Cell>
                        )
                      })}
                    </Row>
                  )
                })}
              </tbody>
            </Table>
          </TableWrapper>
        )}
    </Container>
  )
}
