import React, { useState, ReactNode, useRef, useEffect } from "react";
import { motion } from "framer-motion";
import { checkIsMobile } from "../../utils/checkIsMobile";
import { useDarkMode } from "../../hooks/useDarkMode";
import { createPortal } from "react-dom";
import { usePopOverContext } from "../PopOver/PopOver";

type TooltipProps = {
  title: string;
  children: ReactNode | any;
  position?: "top" | "bottom" | "left" | "right";
  small?: boolean;
  hidden?: boolean;
};

export const Tooltip: React.FC<TooltipProps> = ({
  title,
  children,
  position = "top",
  small,
  hidden = false,
}) => {
  const [visible, setVisible] = useState(false);
  const [isDark] = useDarkMode();
  const anchorRef = useRef<HTMLDivElement | null>(null);
  const isInsidePopOver = usePopOverContext();
  const [coords, setCoords] = useState<{
    top: number;
    left: number;
    transform: string;
  } | null>(null);

  const updatePosition = () => {
    if (!anchorRef.current) return;
    const rect = anchorRef.current.getBoundingClientRect();
    const gap = 8;
    let top = 0;
    let left = 0;
    let transform = "";

    if (position === "top") {
      left = rect.left + rect.width / 2;
      top = rect.top - gap;
      transform = "translate(-50%, -100%)";
    } else if (position === "bottom") {
      left = rect.left + rect.width / 2;
      top = rect.bottom + gap;
      transform = "translate(-50%, 0)";
    } else if (position === "left") {
      top = rect.top + rect.height / 2;
      left = rect.left - gap;
      transform = "translate(-100%, -50%)";
    } else {
      top = rect.top + rect.height / 2;
      left = rect.right + gap;
      transform = "translate(0, -50%)";
    }

    setCoords({ top, left, transform });
  };

  useEffect(() => {
    if (!visible) return;
    updatePosition();
    const onScroll = () => updatePosition();
    const onResize = () => updatePosition();
    window.addEventListener("scroll", onScroll, true);
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("scroll", onScroll, true);
      window.removeEventListener("resize", onResize);
    };
  }, [visible, position]);

  if (checkIsMobile() && isInsidePopOver) {
    return (
      <div
        className="flex items-center justify-center"
        onClick={() => {
          children?.props?.onClick();
        }}
      >
        <span className="w-1/6"></span>
        <span className="text-xs text-nowrap text-gray-600 dark:text-white1-100/25 ">
          {title}
        </span>
        <div className="flex items-center justify-center">{children}</div>
        <span className="w-1/6"></span>
      </div>
    );
  }

  if (checkIsMobile()) {
    return <div className="flex items-center justify-center">{children}</div>;
  }

  return (
    <div
      className="relative inline-block overflow-hidden"
      onMouseEnter={() => !hidden && setVisible(true)}
      onMouseLeave={() => setVisible(false)}
      ref={anchorRef}
    >
      {children}
      {!hidden &&
        visible &&
        coords &&
        createPortal(
          <motion.div
            role="tooltip"
            className={`fixed whitespace-nowrap px-3 py-1 rounded ${
              small ? "text-[10px]" : "text-xs"
            }  text-white bg-black/70 dark:text-black dark:bg-white shadow-md pointer-events-none`}
            style={{
              top: `${coords.top}px`,
              left: `${coords.left}px`,
              transform: coords.transform,
              zIndex: 9999,
            }}
            initial={{ opacity: 0 }}
            animate={{ opacity: isDark ? 1 : 0.9 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.1 }}
          >
            {title}
          </motion.div>,
          document.body
        )}
    </div>
  );
};
