import React, { useRef, useState, useEffect } from "react";
import MuiFormHelperText from "@mui/material/FormHelperText";
import { Tooltip } from "../../Tooltip";
import "./HelperText.styles.scss";

export const HelperText = ({ helper, error, className = "", minWidth }) => {
  const textRef = useRef(null);
  const [isTruncated, setIsTruncated] = useState(false);

  useEffect(() => {
    if (textRef.current) {
      const element = textRef.current;
      setIsTruncated(element.scrollWidth > element.clientWidth);
    }
  }, [helper]);

  if (!helper) return null;

  const textElement = (
    <MuiFormHelperText
      ref={textRef}
      error={error}
      className={`ia-select-helper-text ${className} ${
        error ? "Mui-error" : ""
      }`}
      style={{
        width: minWidth || "240px",
      }}
    >
      {helper}
    </MuiFormHelperText>
  );

  // tooltip visible only when text is truncated
  return isTruncated ? (
    <Tooltip title={helper} variant="tertiary" orientation="right">
      {textElement}
    </Tooltip>
  ) : (
    textElement
  );
};

export default HelperText;
