import { Box } from '@tidbcloud/uikit'
import { useEffect, useRef, useState } from 'react'

export const MiddleEllipsisText = ({ text, width = 200 }: { text: string; width?: number }) => {
  const containerRef = useRef<HTMLDivElement>(null)
  const [displayText, setDisplayText] = useState(text)

  useEffect(() => {
    const el = containerRef.current
    if (!el) return

    const maxWidth = el.offsetWidth
    const style = getComputedStyle(el)
    const font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`
    setDisplayText(middleEllipsis(text, maxWidth, font))
  }, [text])

  return (
    <Box
      component="span"
      ref={containerRef}
      style={{ display: 'block', width, whiteSpace: 'nowrap', overflow: 'hidden', fontFamily: 'moderat' }}
    >
      {displayText}
    </Box>
  )
}

export const middleEllipsis = (text: string, maxWidth: number, font = '400 14px moderat') => {
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  if (!ctx) return text

  ctx.font = font

  const fullWidth = ctx.measureText(text).width
  if (fullWidth <= maxWidth) return text

  const ellipsis = '...'
  let low = 0
  let high = text.length
  let best = ''

  while (low <= high) {
    const mid = Math.floor((low + high) / 2)
    const keepLeft = Math.ceil(mid / 2)
    const keepRight = Math.floor(mid / 2)

    const leftText = text.slice(0, keepLeft)
    const rightText = text.slice(text.length - keepRight)
    const currentText = leftText + ellipsis + rightText
    const currentWidth = ctx.measureText(currentText).width

    if (currentWidth <= maxWidth) {
      best = currentText
      low = mid + 1
    } else {
      high = mid - 1
    }
  }

  return best || ellipsis
}
