"use client"

import * as React from "react"
import { HelpCircle } from "lucide-react"
import { cn } from "@/lib/utils"

interface TooltipHelpProps {
  content: string
  className?: string
}

export function TooltipHelp({ content, className = "" }: TooltipHelpProps) {
  const [isVisible, setIsVisible] = React.useState(false)
  const [position, setPosition] = React.useState({ top: 0, left: 0 })
  const tooltipRef = React.useRef<HTMLDivElement>(null)
  const timeoutRef = React.useRef<NodeJS.Timeout>()

  const handleMouseEnter = (e: React.MouseEvent) => {
    timeoutRef.current = setTimeout(() => {
      const rect = (e.target as HTMLElement).getBoundingClientRect()
      const tooltipRect = tooltipRef.current?.getBoundingClientRect()

      if (tooltipRect) {
        const top = rect.top - tooltipRect.height - 8
        const left = rect.left + (rect.width - tooltipRect.width) / 2

        setPosition({ top, left })
        setIsVisible(true)
      }
    }, 200)
  }

  const handleMouseLeave = () => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    setIsVisible(false)
  }

  React.useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  return (
    <>
      <HelpCircle
        className={cn("h-4 w-4 text-gray-400 hover:text-gray-600 cursor-help", className)}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      />
      {isVisible && (
        <div
          ref={tooltipRef}
          className="fixed z-50 px-3 py-2 text-xs text-white bg-gray-900 rounded-md shadow-lg max-w-xs"
          style={{
            top: position.top,
            left: position.left,
            transition: "opacity 150ms ease-in-out",
          }}
        >
          {content}
          <div className="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900"></div>
        </div>
      )}
    </>
  )
}

// 为了兼容性，导出一个简单的 TooltipProvider
export const TooltipProvider = ({ children }: { children: React.ReactNode }) => <>{children}</>
