import React from "react";
import type { ReactElement } from "react";
import {
  Tooltip as MUITooltip,
  type TooltipProps as MUITooltipProps,
} from "@mui/material";

import type { IconProps } from "../icon/Icon";
import { twMerge } from "../../../tailwind.config";
import { Title } from "./Title";

export interface TooltipProps
  extends Omit<MUITooltipProps, "title" | "open" | "className"> {
  spacing?: "2" | "4" | "6" | "8" | "12";
  tooltip: string | ReactElement;
  shortcutText?: string | string[];
  shortcutIcons?: IconProps["name"][];
  secondaryTooltip?: string | ReactElement;
  tertiaryTooltip?: string | ReactElement;
  open?: boolean;
  /**
   * Whether to allow opening the tooltip.
   *
   * Useful for showing tooltips based on a boolean value.
   */
  disabled?: boolean;
  ESCAPE_className?: string;
}

export const Tooltip = ({
  children,
  tooltip,
  shortcutText,
  shortcutIcons,
  secondaryTooltip,
  tertiaryTooltip,
  placement = "bottom",
  spacing = "8",
  open = undefined,
  disabled = false,
  ESCAPE_className = undefined,
  ...htmlAttributes
}: TooltipProps) => {
  const classes = {
    tooltip: twMerge(
      "m-0 bg-N700 rounded-6 py-4 px-8 shadow-S100",
      ESCAPE_className
    ),
  };

  const props = {
    classes,
    ...htmlAttributes,
  };

  const tooltipTitle = (
    <Title
      tooltip={tooltip}
      shortcutText={shortcutText}
      shortcutIcons={shortcutIcons}
      secondaryTooltip={secondaryTooltip}
      tertiaryTooltip={tertiaryTooltip}
    />
  );

  const disabledProps: Partial<MUITooltipProps> = disabled
    ? {
        disableFocusListener: true,
        disableHoverListener: true,
        disableTouchListener: true,
      }
    : {};

  const controlledOpenStateProps: Partial<MUITooltipProps> =
    open !== undefined
      ? {
          open,
          disableFocusListener: true,
          disableHoverListener: true,
          disableTouchListener: true,
        }
      : {};

  return (
    <MUITooltip
      title={tooltipTitle}
      open={open}
      placement={placement}
      PopperProps={{
        modifiers: [
          {
            name: "offset",
            options: {
              offset: [0, parseInt(spacing, 10)],
            },
          },
          {
            name: "preventOverflow",
            options: {
              padding: 8,
            },
          },
        ],
      }}
      {...controlledOpenStateProps}
      {...disabledProps}
      {...props}
    >
      {children}
    </MUITooltip>
  );
};
