import { type MouseEvent, useState } from 'react';

import { truncate } from 'lodash-es';
import * as colors from '@material-hu/mui/colors';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography, { type TypographyProps } from '@material-hu/mui/Typography';

import { type MUITooltipProps } from '@material-hu/components/design-system/Tooltip/types';

type TextOverflowTipProps = {
  primary: string;
  typographyProps?: TypographyProps;
  tooltipProps?: Partial<MUITooltipProps>;
  length?: number;
  lineClamp?: number;
};

/**
 * @deprecated Use `@material-hu/components/composed-components/TextOverflowTip` instead
 */
export const TextOverflowTip = ({
  primary,
  typographyProps = {},
  tooltipProps,
  length,
  lineClamp,
}: TextOverflowTipProps) => {
  const [tooltipEnabled, setTooltipEnabled] = useState(false);
  const shouldTruncate = length && length < primary.length && !lineClamp;

  const handleShouldShow = ({ currentTarget }: MouseEvent<Element>) => {
    if (shouldTruncate) {
      setTooltipEnabled(true);
      return;
    }

    if (lineClamp && currentTarget.scrollHeight > currentTarget.clientHeight) {
      setTooltipEnabled(true);
    }

    if (currentTarget.scrollWidth > currentTarget.clientWidth) {
      setTooltipEnabled(true);
    }
  };

  return (
    <Tooltip
      title={primary}
      open={tooltipEnabled}
      onClose={() => setTooltipEnabled(false)}
      placement="top"
      {...tooltipProps}
      componentsProps={{
        ...tooltipProps?.componentsProps,
        tooltip: {
          sx: {
            backdropFilter: 'blur(2px)',
            bgcolor: `${colors.blueGrey[900]}B3`,
            fontWeight: 'fontWeightBold',
            lineHeight: '14px',
            fontSize: '10px',
            p: 1,
            ...tooltipProps?.componentsProps?.tooltip?.sx,
          },
        },
      }}
    >
      <Typography
        onMouseEnter={handleShouldShow}
        noWrap={!shouldTruncate}
        {...typographyProps}
        sx={{
          ...(lineClamp && {
            WebkitLineClamp: lineClamp,
            WebkitBoxOrient: 'vertical',
            display: '-webkit-box',
            whiteSpace: 'normal !important',
            overflowWrap: 'break-word',
          }),
          ...(!lineClamp &&
            !length && {
              textOverflow: 'ellipsis',
              overflow: 'hidden',
              whiteSpace: 'nowrap',
            }),
          width: '100%',
          ...(!typographyProps?.variant && {
            fontSize: 'inherit',
            fontWeight: 'inherit',
          }),
          ...typographyProps?.sx,
        }}
      >
        {shouldTruncate ? truncate(primary, { length }) : primary}
      </Typography>
    </Tooltip>
  );
};

export default TextOverflowTip;
