import React, { useEffect, useRef, useState } from "react";
import {
  DialogTitle as MuiDialogTitle,
  DialogTitleProps as MuiDialogTitleProps,
} from "@mui/material";

import { Button } from "../button/Button";
import { Typography } from "../typography/Typography";
import { Tooltip } from "../tooltip/Tooltip";
import { twMerge } from "../../../tailwind.config";
import { DialogProps } from "./Dialog";

export interface DialogTitleProps
  extends Omit<MuiDialogTitleProps, "className"> {
  children: string;
  onClose?: DialogProps["onClose"];
  ESCAPE_className?: string;
}

function useEllipsisDetection(children: string) {
  const measureRef = useRef<HTMLElement>(null);
  const [isEllipsed, setIsEllipsed] = useState(false);

  useEffect(() => {
    setIsEllipsed(
      measureRef.current !== null && isEllipsisActive(measureRef.current)
    );
  }, [measureRef, children]);

  return [measureRef, isEllipsed] as const;
}

function useDialogTitleStyles() {
  const classes = {
    root: "p-16 pl-24 flex justify-between items-center border-0 border-b border-solid border-N30",
    titleText: "mr-16 overflow-hidden whitespace-nowrap overflow-ellipsis",
    button: "flex-shrink-0",
    tooltip: "max-w-full",
  };

  return classes;
}

export const DialogTitle: React.FC<DialogTitleProps> = ({
  children,
  onClose,
  ESCAPE_className,
  ...other
}) => {
  const { titleText, button, tooltip, ...classes } = useDialogTitleStyles();

  const [measureRef, isEllipsed] = useEllipsisDetection(children);

  return (
    <MuiDialogTitle
      classes={{ ...classes, root: twMerge(classes.root, ESCAPE_className) }}
      {...other}
    >
      <Tooltip
        disabled={!isEllipsed}
        tooltip={children}
        ESCAPE_className={tooltip}
      >
        <Typography
          size="300"
          color="main"
          weight="bold"
          ESCAPE_className={titleText}
          ref={measureRef}
        >
          {children}
        </Typography>
      </Tooltip>
      {onClose && (
        <Button
          variant="tertiary"
          // TODO: localize this when we find a way
          title="Sluiten"
          aria-label="Sluiten"
          icon="xmark"
          onClick={(e) => onClose(e, undefined)}
          ESCAPE_className={button}
        />
      )}
    </MuiDialogTitle>
  );
};

/** Checks if the element is truncated with an ellipsis. */
function isEllipsisActive(e: HTMLElement) {
  return e.scrollWidth > e.clientWidth;
}
