import { Typography, type TypographyProps } from '@mui/material';

import { styled } from '../Theme';
import { withDeprecated } from '../Util/deprecate';

export interface TextCollapseProps {
  children: string;
  maxWidth: string | number;
  startChars?: number;
  endChars?: number;
  scaleFactor?: number;
  style?: React.CSSProperties;
  fontType?: 'monospace' | 'normal';
}

function TextCollapse({
  children,
  maxWidth,
  startChars = 5,
  endChars = 5,
  scaleFactor = 0.45,
  style = undefined,
  fontType = 'normal',
  ...rest
}: TextCollapseProps) {
  if (typeof children !== 'string') {
    return null;
  }

  const isMonospace = fontType === 'monospace';

  // 由于 css 样式产生的省略号长度是不确定的，所以目前 startChars 的长度只能让开发者自己去加上‘省略号’的宽度去设置这个值，要想完美的实现目标功能，最好是改用 js 动态修改文本内容来实现
  const startWidth = isMonospace ? `${startChars}ch` : `${scaleFactor * (startChars + 3)}em`;
  const endWidth = isMonospace ? `${endChars}ch` : `${scaleFactor * endChars}em`;
  const styles = Object.assign(
    isMonospace ? { fontFamily: '"Courier New", Courier, monospace' } : {},
    { fontSize: 'inherit', color: 'inherit', fontWeight: 'inherit', maxWidth },
    style
  );

  const [startPart, endPart] = [
    children.slice(0, children.length - endChars),
    children.slice(children.length - endChars),
  ];

  return (
    <Container component="span" style={styles} startwidth={startWidth} endwidth={endWidth} {...rest}>
      <span className="start-part">{startPart}</span>
      <span className="end-part">{endPart}</span>
    </Container>
  );
}

export default withDeprecated(TextCollapse, { name: 'TextCollapse' });

type ContainerProps = {
  startwidth: string;
  endwidth: string;
};

const Container = styled(Typography)<ContainerProps & TypographyProps>`
  display: inline-flex;
  align-items: center;
  justify-content: start;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;

  .start-part,
  .end-part {
    display: inline-block;
    vertical-align: bottom;
    white-space: nowrap;
    overflow: hidden;
  }
  .start-part {
    max-width: calc(100% - ${(props) => props.endwidth});
    min-width: ${(props) => props.startwidth};
    text-overflow: ellipsis;
  }
  .end-part {
    max-width: calc(100% - ${(props) => props.startwidth});
    direction: rtl;
  }
`;
