import React from 'react'
import type { HTMLEditor } from '../../lib'
import { TextToolbar } from './components/TextToolbar'
import useSelectionFormatting from './hooks/useSelectionFormatting'

interface Position {
  top: number
  left: number
  width: number
  height: number
  bottom: number
  right: number
}

interface TooltipProps {
  editor: HTMLEditor | null | undefined
  element: HTMLElement | null | undefined
  position: Position | null
  containerRef: React.RefObject<HTMLDivElement | null>
}

export const Tooltip: React.FC<TooltipProps> = ({
  editor,
  element,
  position,
  containerRef,
}) => {
  if (!editor || !position) {
    return null
  }

  const contaierRect =
    containerRef.current?.getBoundingClientRect() || ({} as DOMRect)
  const { left = 0, top = 0 } = contaierRect

  const toolWidth = 288
  const toolHeight = 36
  const marginXPad = 32

  // 右边界限制
  let releativeLeft = position.left - toolWidth / 2
  if (position.left + toolWidth + left > window.innerWidth) {
    releativeLeft = window.innerWidth - toolWidth - left - marginXPad
  }
  // 左边界限制
  if(releativeLeft < 5) {
    releativeLeft = 5
  }

  let releativeBottom = position.bottom
  if (releativeBottom + toolHeight + 25 > window.innerHeight) {
    releativeBottom = position.top - toolHeight - 15
  }

  const tooltipStyle: React.CSSProperties = {
    position: 'absolute',
    top: `${releativeBottom + 10}px`,
    left: `${releativeLeft}px`,
    zIndex: 100000,
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const formatState = useSelectionFormatting(editor)

  return (
    <div style={tooltipStyle} className='html-editor-floating-toolbar'>
      <TextToolbar editor={editor} formatState={formatState}/>
    </div>
  )
}

export default Tooltip
