import React, { useState } from 'react';
import AntdTypography from 'antd/es/typography';
import { getPrefixCls } from '../config-provider';

import './index.less';

const defaultEllipsis = {
  expandable: true,
  symbol: '展开',
};

const Typography = props => {
  const { prefixCls: customizePrefixCls, ...restProps } = props;
  const prefixCls = getPrefixCls('typography', customizePrefixCls);
  return <AntdTypography prefixCls={prefixCls} {...restProps} />;
};

const Paragraph = props => {
  const {
    prefixCls: customizePrefixCls,
    ellipsis,
    children,
    ...restProps
  } = props;
  const prefixCls = getPrefixCls('typography', customizePrefixCls);
  const [expanded, setExpanded] = useState(false);
  let ellipsisProps = {};
  let childrenNode = children;
  if (ellipsis) {
    ellipsisProps = {
      ...defaultEllipsis,
      onExpand: () => {
        setExpanded(true);
      },
      fold: '收起',
      ...ellipsis,
    };
    if (expanded) {
      childrenNode = (
        <>
          {children}
          <span
            className={`${prefixCls}-fold`}
            onClick={() => setExpanded(false)}
          >
            {ellipsisProps.fold}
          </span>
        </>
      );
    }
  } else {
    ellipsisProps = false;
  }

  if (!ellipsis || expanded) {
    return (
      <AntdTypography.Paragraph
        key="expanded"
        {...restProps}
        ellipsis={false}
        prefixCls={prefixCls}
      >
        {childrenNode}
      </AntdTypography.Paragraph>
    );
  }

  return (
    <AntdTypography.Paragraph
      key="unexpanded"
      {...restProps}
      ellipsis={ellipsisProps}
      prefixCls={prefixCls}
    >
      {childrenNode}
    </AntdTypography.Paragraph>
  );
};

const Text = props => {
  const { prefixCls: customizePrefixCls, ...restProps } = props;
  const prefixCls = getPrefixCls('typography', customizePrefixCls);
  return <AntdTypography.Text {...restProps} prefixCls={prefixCls} />;
};

const Title = props => {
  const { prefixCls: customizePrefixCls, ...restProps } = props;
  const prefixCls = getPrefixCls('typography', customizePrefixCls);
  return <AntdTypography.Title {...restProps} prefixCls={prefixCls} />;
};

const Link = props => {
  const { prefixCls: customizePrefixCls, ...restProps } = props;
  const prefixCls = getPrefixCls('typography', customizePrefixCls);
  return <AntdTypography.Link {...restProps} prefixCls={prefixCls} />;
};

Typography.Paragraph = Paragraph;
Typography.Text = Text;
Typography.Title = Title;
Typography.Link = Link;

export default Typography;
