import { getClassNames } from '@websolutespa/bom-core';
import React, { ReactNode } from 'react';
import { UrlObject } from 'url';
import { Button } from '../button/button';
import { Link, LinkProps } from '../link/link';

type Url = string | UrlObject;

type Props = {
  href?: Url;
  onClick?: (event: React.MouseEvent) => void
  className?: string,
  children?: ReactNode,
};

type NativeAttrs = Omit<React.AnchorHTMLAttributes<any>, keyof Props>;

type NativeLinkAttrs = Omit<NativeAttrs, keyof LinkProps>;

export type BreadcrumbItemProps = Props & NativeLinkAttrs;

export const BreadcrumbItem = React.forwardRef<HTMLAnchorElement, React.PropsWithChildren<BreadcrumbItemProps>>(({
  children,
  className = '',
  href,
  onClick,
  ...props
}: BreadcrumbItemProps, ref: React.Ref<HTMLAnchorElement>) => {

  const onClick_ = (event: React.MouseEvent) => {
    onClick && onClick(event);
  };

  const classNames = getClassNames('breadcrumb-item', className);
  if (href) {
    return (
      <Link ref={ref} className={classNames} href={href} {...props}>
        <Button variant="link" as="a" onClick={onClick_}>
          {children}
        </Button>
      </Link>
    );
  }
  return (
    <span className={classNames}>
      {children}
    </span>
  );
});

BreadcrumbItem.displayName = 'BreadcrumbItem';
