import React, { ReactElement } from 'react';
import css from '../../utils/css';

import Icon from '../Icon';
import BreadcrumbItem from './BreadcrumbItem';
import {
  SingleBreadcrumbContainer,
  BreadcrumbContainer,
} from './StyledBreadcrumb';

import { CommonProps } from '../common';
import { isNonEmptyArray } from '../../fp/NonEmptyArray';

export interface BreadcrumbProps extends CommonProps {
  /**
   * All breadcrumbs to display. Use withRouter if you wish to use Breadcrumb with react-router.
   */
  items: { href: string; text: string; withRouter?: boolean }[];
}

const Breadcrumb = ({
  items,
  id,
  className,
  style,
  sx = {},
  'data-test-id': dataTestId,
}: BreadcrumbProps): ReactElement => {
  const breadcrumbLength = items.length;

  if (isNonEmptyArray(items) && breadcrumbLength === 1) {
    return (
      <SingleBreadcrumbContainer
        id={id}
        className={className}
        style={{ ...style, ...css(sx) }}
        data-test-id={dataTestId}
      >
        <Icon icon="single-left-arrow" />
        <BreadcrumbItem
          href={items[0].href}
          text={items[0].text}
          withRouter={items[0].withRouter}
          withSeparator={false}
        />
      </SingleBreadcrumbContainer>
    );
  }

  return (
    <BreadcrumbContainer
      id={id}
      className={className}
      style={{ ...style, ...css(sx) }}
      data-test-id={dataTestId}
    >
      {items.map((item, index) => (
        <BreadcrumbItem
          key={item.text}
          text={item.text}
          href={item.href}
          withRouter={item.withRouter}
          current={index + 1 === breadcrumbLength}
        />
      ))}
    </BreadcrumbContainer>
  );
};

export default Breadcrumb;
