import type { PropsWithChildren, HTMLProps } from 'react'
import { memo, useRef } from 'react'
import { createPortal } from 'react-dom'

import { isMobileDevice, KEYBOARD_KEYS } from 'config'

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

import { Tooltip } from '../TabStats/styled'
import { CellContainer } from './styled'

type CellProps = {
  anchorId?: string,
  as?: 'td' | 'th',
  clickable?: boolean,
  columnWidth?: number,
  sorted?: boolean,
  tooltipText?: string,
} & HTMLProps<HTMLTableCellElement>

const CellFC = ({
  anchorId,
  as,
  children,
  clickable,
  columnWidth,
  onClick,
  sorted,
  tooltipText,
}: PropsWithChildren<CellProps>) => {
  const cellRef = useRef<HTMLTableCellElement | null>(null)

  const {
    isTooltipShown,
    onMouseLeave,
    onMouseOver,
    tooltipStyle,
  } = useTooltip()

  const modalRoot = useModalRoot()

  useEventListener({
    callback: (e) => {
      if (e.key !== KEYBOARD_KEYS.Enter) return

      // @ts-expect-error
      onClick()
    },
    event: 'keydown',
    target: cellRef,
  })

  return (
    <CellContainer
      ref={cellRef}
      as={as}
      onClick={onClick}
      clickable={clickable}
      columnWidth={columnWidth}
      sorted={sorted}
      onMouseOver={tooltipText && !isMobileDevice ? onMouseOver({
        anchorId,
        horizontalPosition: 'right',
        tooltipText,
        verticalPosition: 'top',
      }) : undefined}
      onMouseLeave={tooltipText && !isMobileDevice ? onMouseLeave : undefined}
    >
      {children}
      {isTooltipShown && modalRoot.current && createPortal(
        <Tooltip style={tooltipStyle}>
          {tooltipText}
        </Tooltip>,
        modalRoot.current,
      )}
    </CellContainer>
  )
}

export const Cell = memo(CellFC)
