import React, { useContext } from 'react';
import {
  Anchor as OldAnchor,
  AnchorProps as OldAnchorProps,
  ConfigProvider,
  AnchorLinkProps as OldAnchorLinkProps,
} from 'antd';
import classNames from 'classnames';
import './index.less';

export interface AnchorProps extends OldAnchorProps {
  hideLine?: boolean;
}

export interface AnchorLinkProps extends OldAnchorLinkProps {
  links?: OldAnchorLinkProps[];
  level?: number;
}

function Anchor(props: AnchorProps) {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const { hideLine = false } = props;
  const prefixCls = getPrefixCls('btri-anchor');
  return (
    <OldAnchor
      {...props}
      className={classNames(`${prefixCls}`, props.className, {
        [`${prefixCls}-hide-line`]: hideLine,
      })}
    ></OldAnchor>
  );
}

function RenderLink(links: AnchorLinkProps[], level = 1) {
  const cls = classNames(`btri-anchor-level-${level}`, 'btri-anchor-level');
  return links.map(link => {
    if (link.links) {
      return (
        <>
          <div data-level={level} className={cls}>
            <OldAnchor.Link
              href={link.href}
              title={link.title}
              {...link}
            ></OldAnchor.Link>
          </div>

          {link.links && RenderLink(link.links, level + 1)}
        </>
      );
    }
    return (
      <div data-level={level} className={cls}>
        <OldAnchor.Link
          href={link.href}
          title={link.title}
          {...link}
        ></OldAnchor.Link>
      </div>
    );
  });
}

Anchor.Link = (props: AnchorLinkProps) => {
  if (props.links) {
    return <>{RenderLink(props.links)}</>;
  }
  return <OldAnchor.Link {...props}></OldAnchor.Link>;
};

export { Anchor };
