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

import { truncate } from 'lodash-es';
import * as colors from '@material-hu/mui/colors';
import { alpha } from '@material-hu/mui/styles';
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;
  secondary?: string;
  typographyProps?: TypographyProps;
  tooltipProps?: Partial<MUITooltipProps>;
  length?: number;
  lineClamp?: number;
};

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: alpha(colors.blueGrey[900], 0.7),
            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',
            overflowWrap: 'break-word',
          }),
          ...(!lineClamp &&
            !length && {
              textOverflow: 'ellipsis',
              overflow: 'hidden',
              whiteSpace: 'nowrap',
            }),
          width: '100%',
          ...typographyProps?.sx,
        }}
      >
        {shouldTruncate ? truncate(primary, { length }) : primary}
      </Typography>
    </Tooltip>
  );
};

export default TextOverflowTip;
