import { createPortal } from 'react-dom'

import { isMobileDevice, ProfileTypes } from 'config'

import type { Event, Team } from 'requests'

import {
  useTooltip,
  usePageParams,
  useModalRoot,
} from 'hooks'

import { Name } from 'features/Name'
import { T9n } from 'features/T9n'
import { useLexicsStore } from 'features/LexicsStore'

import {
  Avatar,
  Button,
  EventInfo,
  EventDesc,
  Title,
  SubTitle,
  EventTime,
  EventLike,
} from '../TabEvents/styled'
import { Tooltip } from '../TabStats/styled'

type Props = {
  active?: boolean,
  disabled?: boolean,
  event: Event,
  isHomeTeam: boolean,
  onClick: () => void,
  team?: Team,
}

export const EventButton = ({
  active,
  disabled,
  event,
  isHomeTeam,
  onClick,
  team,
}: Props) => {
  const { sportType } = usePageParams()
  const {
    isTooltipShown,
    onMouseLeave,
    onMouseOver,
    tooltipStyle,
    tooltipText,
  } = useTooltip()
  const modalRoot = useModalRoot()
  const { suffix } = useLexicsStore()

  const {
    c: clearTime,
    l: lexica,
    p: playerId,
    pl: playerName,
    sc1: score1,
    sc2: score2,
    t: teamId,
  } = event

  const avatarId = playerId || teamId
  const profileType = playerId
    ? ProfileTypes.PLAYERS
    : ProfileTypes.TEAMS
  const nameObj = playerName || team

  return (
    <Button
      onClick={onClick}
      active={!!active}
      disabled={disabled}
      isHomeTeam={isHomeTeam}
      like={event.like}
    >
      {avatarId && (
        <Avatar
          id={avatarId}
          isHomeTeam={isHomeTeam}
          isPlayer={Boolean(playerId)}
          profileType={profileType}
          sportType={sportType}
        />
      )}
      <EventInfo>
        {event.like && (
          <EventLike src='/images/like-active-icon.svg' />
        )}
        <EventTime>
          {clearTime}
        </EventTime>
        <EventDesc>
          <Title>
            <T9n t={lexica} />
            {(score1 || score2) && ` (${score1}-${score2})`}
          </Title>
          <SubTitle
            onMouseOver={isMobileDevice ? undefined : onMouseOver({
              horizontalPosition: 'right',
              indent: 15,
              tooltipText: nameObj?.[`name_${suffix}`] || '',
            })}
            onMouseLeave={isMobileDevice ? undefined : onMouseLeave}
          >
            {playerName?.num}{' '}
            {(playerId || teamId) && nameObj && <Name nameObj={nameObj} />}
          </SubTitle>
        </EventDesc>
      </EventInfo>
      {isTooltipShown && modalRoot.current && createPortal(
        <Tooltip style={tooltipStyle}>
          {tooltipText}
        </Tooltip>,
        modalRoot.current,
      )}
    </Button>
  )
}
