import React, { forwardRef } from "react";
import classNames from "classnames";
import { isChildOfType } from "../_util/is-child-of-type";
import { StyledProps } from "../_type";
import { useConfig } from "../_util/config-context";
import { forwardRefWithStatics } from "../_util/forward-ref-with-statics";

interface BreadcrumbItemProps extends StyledProps {
  current?: boolean;
  children?: React.ReactNode;
}

export const BreadcrumbItem = forwardRef(function BreadcrumbItem(
  { current, children, className, ...props }: BreadcrumbItemProps,
  ref: React.Ref<HTMLLIElement>
) {
  const { classPrefix } = useConfig();

  if (typeof children === "string") {
    // eslint-disable-next-line no-param-reassign
    children = <span>{children}</span>;
  }

  return (
    <li
      ref={ref}
      className={classNames(`${classPrefix}-breadcrumb__item`, className)}
      {...props}
    >
      {React.isValidElement<StyledProps>(children)
        ? React.cloneElement(children, {
            className: classNames(
              children.props.className,
              `${classPrefix}-breadcrumb__item-title`,
              {
                "is-current": current,
              }
            ),
          })
        : children}
    </li>
  );
});

BreadcrumbItem.displayName = "BreadcrumbItem";

export interface BreadcrumbProps extends StyledProps {
  /**
   * 导航内容
   */
  children?: React.ReactNode;

  /**
   * 较大字号的样式，可用于 Layout.Content 标题处
   */
  large?: boolean;
}

export const Breadcrumb = forwardRefWithStatics(
  function Breadcrumb(
    { large, children, className, ...props }: BreadcrumbProps,
    ref: React.Ref<HTMLOListElement>
  ) {
    const { classPrefix } = useConfig();
    return (
      <ol
        ref={ref}
        className={classNames(`${classPrefix}-breadcrumb`, className, {
          [`${classPrefix}-breadcrumb--fz-large`]: large,
        })}
        {...props}
      >
        {React.Children.map(children, (child, index) => {
          if (
            isChildOfType(child, BreadcrumbItem) &&
            index === React.Children.count(children) - 1
          ) {
            return React.cloneElement(child, {
              current: true,
            });
          }
          return child;
        })}
      </ol>
    );
  },
  {
    Item: BreadcrumbItem,
  }
);

Breadcrumb.displayName = "Breadcrumb";
