import React, { ReactNode } from 'react';
import styled from 'styled-components';
import { UIComponent, UIStyledComponentProps } from '../types';
import { getCssResponsive } from '../utils';
import { BreadcrumbSeparator } from './breadcrumb-separator';

type Props = {
  separator?: string | ReactNode;
  children?: ReactNode;
};

export type BreadcrumbProps = UIStyledComponentProps<Props>;

export type BreadcrumbComponent<C extends React.ElementType = 'nav'> = UIComponent<C, Props>;

const StyledBreadcrumb = styled.div<BreadcrumbProps>`
  display: flex;
  align-items: center;

  .breadcrumb-item {
    display: inline-flex;
    align-items: center;
  }

  .breadcrumb-separator,
  .breadcrumb-item:not(.link) {
    color: var(--color-neutral-500);
  }

  & > .breadcrumb-separator:last-child {
    display: none;
  }

  svg {
    width: 1em;
    height: 1em;
    margin: 0 0.3em;
  }

  ${props => getCssResponsive(props)}
`;

export const BreadcrumbBase: BreadcrumbComponent = ({ children, as = 'nav' as React.ElementType, separator = '/', className = '', ...props }) => {
  const items = React.Children.toArray(children);
  const withSeparatorChildren = items.map((item, i) => {
    if (!React.isValidElement(item)) {
      return item;
    }
    const last = items[i - 1];
    const lastIsSeparator = React.isValidElement(last) && last.type === BreadcrumbSeparator;
    const currentIsSeparator = item.type === BreadcrumbSeparator;
    if (!lastIsSeparator && !currentIsSeparator && i > 0) {
      return (
        <React.Fragment key={i}>
          <BreadcrumbSeparator>{separator}</BreadcrumbSeparator>
          {item}
        </React.Fragment>
      );
    }
    return item;
  });
  return (
    <StyledBreadcrumb as={as} className={className} {...props}>
      {withSeparatorChildren}
    </StyledBreadcrumb>
  );
};
