import { Children } from 'react';
import PropTypes from 'prop-types';
import { Box, Tooltip, tooltipClasses } from '@mui/material';
import { styled } from '../Theme';
import { CopyButton } from '../ClickToCopy';

const StyledTooltip = styled(({ className, ...props }) => <Tooltip {...props} classes={{ popper: className }} />)({
  [`& .${tooltipClasses.tooltip}`]: {
    maxWidth: 360,
    wordBreak: 'break-all',
  },
});

// 递归, 将 text (string) 部分替换为 CompactText (保持元素结构)
// eslint-disable-next-line react/prop-types
function RecursiveWrapper({ children, ...rest }) {
  const wrappedChildren = Children.map(children, (child) => {
    if (typeof child === 'string') {
      return <CompactText {...rest}>{child}</CompactText>;
    }
    if (child.props && child.props.children) {
      return (
        <child.type {...child.props}>
          <RecursiveWrapper {...rest}>{child.props.children}</RecursiveWrapper>
        </child.type>
      );
    }
    return child;
  });
  return wrappedChildren;
}

/**
 * 紧凑文本组件 (显示首尾, 中间截断显示省略号), 仅考虑等宽字体的情况
 */
export default function CompactText({ startChars = 6, endChars = 6, children, showCopyButtonInTooltip = false }) {
  if (typeof children !== 'string') {
    return (
      <RecursiveWrapper startChars={startChars} endChars={endChars} showCopyButtonInTooltip={showCopyButtonInTooltip}>
        {children}
      </RecursiveWrapper>
    );
  }

  // stopPropagation: 当 tooltip 处于 link 中时, 避免点击复制时触发链接跳转
  const tooltipContent = (
    <Box
      onClick={(e) => e.stopPropagation()}
      sx={{
        display: 'flex',
        alignItems: 'center',
        lineHeight: 1,
      }}>
      <Box>{children}</Box>
      {showCopyButtonInTooltip && (
        <CopyButton content={children} showTooltip={false} style={{ fontSize: 16, marginLeft: 4 }} />
      )}
    </Box>
  );

  return (
    <StyledTooltip title={tooltipContent} placement="top">
      <span>
        {children.slice(0, startChars)}...{children.slice(children.length - endChars)}
      </span>
    </StyledTooltip>
  );
}

CompactText.propTypes = {
  startChars: PropTypes.number,
  endChars: PropTypes.number,
  children: PropTypes.node.isRequired,
  // 在 tooltip 中完整地址后显示复制按钮
  showCopyButtonInTooltip: PropTypes.bool,
};
