import {
  autoPlacement,
  autoUpdate,
  offset,
  shift,
  useFloating,
  useHover,
  useInteractions,
} from "@floating-ui/react";
import type React from "react";
import { useState } from "react";

import createUseStyles from "./theme/createUseStyles";
import { cn } from "./util/cn";

const useStyles = createUseStyles({
  tooltip: {
    fontWeight: "normal",
    opacity: 0.9,
    zIndex: 1000,
  },
});

export default function Tooltip({
  children,
  content,
  isDisabled = false,
  offsetDistance = 4,
}: React.PropsWithChildren<{
  content: React.ReactNode;
  isDisabled?: boolean;
  offsetDistance?: number;
}>) {
  const classes = useStyles();
  const [isOpen, setIsOpen] = useState(false);

  const { refs, floatingStyles, context } = useFloating({
    middleware: [offset(offsetDistance), autoPlacement(), shift()],
    onOpenChange: setIsOpen,
    open: isOpen && !isDisabled,
    whileElementsMounted: autoUpdate,
  });

  const hover = useHover(context);
  const { getReferenceProps, getFloatingProps } = useInteractions([hover]);

  if (isDisabled || content === undefined) {
    return <>{children}</>;
  }

  return (
    <>
      <div
        ref={refs.setReference}
        {...getReferenceProps()}
      >
        {children}
      </div>
      {isOpen && (
        <div
          ref={refs.setFloating}
          style={floatingStyles}
          className={cn("bg-black border-white border-radius-s text-white font-size-xs font-lineHeight-s py-xxs px-s", classes.tooltip)}
          {...getFloatingProps()}
        >
          {content}
        </div>
      )}
    </>
  );
};
