import React, { useContext, useEffect, useState } from 'react';
import {
  ConfigProvider,
  Breadcrumb,
  BreadcrumbProps,
  BreadcrumbItemProps,
  DropDownProps,
} from 'antd';
import classNames from 'classnames';
import './style/index.less';
import { Tooltip, Icon } from '../index';
const AntdBreadcrumbItem = Breadcrumb.Item;
export interface BreadcrumbItemInterface extends React.FC<BreadcrumbItemProps> {
  __ANT_BREADCRUMB_ITEM: boolean;
}

type breadcrumbItemProps = {
  dropDownConfig?: DropDownProps;
  isOutEllipsis?: boolean;
  iconName?: string;
  maxLength?: number;
};
const BreadcrumbItem = (props: BreadcrumbItemProps & breadcrumbItemProps) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-breadcrumb');
  const {
    dropDownConfig,
    iconName,
    isOutEllipsis,
    maxLength = 10,
    ...other
  } = props;

  const [isEllipsis, setEllipsis] = useState<boolean>(false);
  useEffect(() => {
    const data = props.children;
    setEllipsis(typeof data == 'string' && data.length > maxLength);
  }, [props.children]);

  return (
    <>
      <AntdBreadcrumbItem
        {...other}
        className={classNames(
          `${prefixCls}-item`,
          `${isEllipsis && prefixCls + '-toopTipsClass'}`,
          `${props.className}`,
        )}
        dropdownProps={{
          overlayClassName: `${prefixCls}-BreadCrumb-DropDown ${props?.dropDownConfig?.overlayClassName}`,
          ...dropDownConfig,
        }}
      >
        {isEllipsis ? (
          <Tooltip placement="topLeft" title={props.children}>
            {props.children}
          </Tooltip>
        ) : props.overlay && !isOutEllipsis ? (
          <div className={`${prefixCls}-overlay`}>
            {props.children}
            <Icon iconName="DownSmall" />
          </div>
        ) : iconName ? (
          <>
            <Icon iconName={iconName} className={`${prefixCls}-Icons`} />
            {props.children}
          </>
        ) : (
          props.children
        )}
      </AntdBreadcrumbItem>
    </>
  );
};
BreadcrumbItem.__ANT_BREADCRUMB_ITEM = true;
export default BreadcrumbItem;
