"use client";

import React, { useState, useRef, useEffect } from "react";

export const Tooltip = ({
  content,
  children,
  position = "top",
  showIcon = true,
  iconClassName = "",
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const [tooltipStyle, setTooltipStyle] = useState({});
  const tooltipRef = useRef(null);
  const iconRef = useRef(null);

  const showTooltip = () => setIsVisible(true);
  const hideTooltip = () => setIsVisible(false);

  // Position the tooltip when it becomes visible
  useEffect(() => {
    if (isVisible && iconRef.current && tooltipRef.current) {
      const triggerRect = iconRef.current.getBoundingClientRect();
      const tooltipRect = tooltipRef.current.getBoundingClientRect();
      const spacing = 8; // Space between trigger and tooltip

      let style = {};

      switch (position) {
        case "top":
          style = {
            left:
              triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2,
            top: triggerRect.top - tooltipRect.height - spacing,
          };
          break;
        case "bottom":
          style = {
            left:
              triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2,
            top: triggerRect.bottom + spacing,
          };
          break;
        case "left":
          style = {
            left: triggerRect.left - tooltipRect.width - spacing,
            top:
              triggerRect.top + triggerRect.height / 2 - tooltipRect.height / 2,
          };
          break;
        case "right":
          style = {
            left: triggerRect.right + spacing,
            top:
              triggerRect.top + triggerRect.height / 2 - tooltipRect.height / 2,
          };
          break;
      }

      // Adjust if tooltip would go off-screen
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;

      if (style.left < 10) style.left = 10;
      if (style.left + tooltipRect.width > viewportWidth - 10) {
        style.left = viewportWidth - tooltipRect.width - 10;
      }

      if (style.top < 10) style.top = 10;
      if (style.top + tooltipRect.height > viewportHeight - 10) {
        style.top = viewportHeight - tooltipRect.height - 10;
      }

      // Convert to fixed position
      style.position = "fixed";
      style.left = `${style.left}px`;
      style.top = `${style.top}px`;

      setTooltipStyle(style);
    }
  }, [isVisible, position]);

  return (
    <div className="inline-flex items-center relative">
      {children}

      {showIcon && (
        <div
          ref={iconRef}
          className={`inline-flex items-center justify-center ml-1 cursor-help ${iconClassName}`}
          onMouseEnter={showTooltip}
          onMouseLeave={hideTooltip}
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-4 w-4 text-gray-400 hover:text-gray-500"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
        </div>
      )}

      {isVisible && (
        <div
          ref={tooltipRef}
          className="z-50 bg-gray-800 text-white text-xs rounded py-1 px-2 max-w-xs shadow-lg pointer-events-none"
          style={{
            ...tooltipStyle,
          }}
        >
          {content}
          <div
            className={`absolute w-2 h-2 bg-gray-800 transform rotate-45 ${
              position === "top"
                ? "bottom-0 translate-y-1/2"
                : position === "bottom"
                ? "top-0 -translate-y-1/2"
                : position === "left"
                ? "right-0 translate-x-1/2"
                : "left-0 -translate-x-1/2"
            }`}
            style={{
              left:
                position === "top" || position === "bottom"
                  ? "calc(50% - 4px)"
                  : "",
              top:
                position === "left" || position === "right"
                  ? "calc(50% - 4px)"
                  : "",
            }}
          />
        </div>
      )}
    </div>
  );
};
