import React from 'react'
import type { HTMLEditor } from '../../lib'
import { isBlockElement, isImageElement, isTextElement } from '../../lib'
import { TextToolbar } from './components/TextToolbar'
import { BlockToolbar } from './components/BlockToolbar'
import { ImageToolbar } from './components/ImageToolbar'

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>
  className?: string
}

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

  const isText = isTextElement(element)
  const isBlock = isBlockElement(element)
  const isImage = isImageElement(element)

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

  const toolWidth = isText ? 365 : 105
  const toolHeight = 36
  // 右边界限制
  let releativeLeft = position.left
  if (position.left + toolWidth + left > window.innerWidth) {
    releativeLeft = window.innerWidth - toolWidth - left
  }

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

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

  return (
    <div style={tooltipStyle} className={`html-editor-floating-toolbar ${className}`}>
      {isText && <TextToolbar editor={editor} element={element} />}
      {isBlock && <BlockToolbar editor={editor} element={element} />}
      {isImage && <ImageToolbar editor={editor} element={element} />}
    </div>
  )
}

export default Tooltip
