import React from 'react';
import { Breadcrumb, Glyphicon, Label, Navbar } from 'react-bootstrap';
import { Link, useLocation } from 'react-router-dom';
import styles from './BreadCrumbs.module.css';

function BreadCrumbs(props) {
  const { breadcrumbs } = props;
  const { state } = useLocation();

  if (state && state.back) {
    const { title, pathname, search, scrollPosition } = state.back;
    return (
      <Navbar className={styles.backBar} fluid>
        <Link to={{ pathname, search, state: { scrollPosition } }}>
          <Glyphicon glyph="arrow-left" style={{ marginRight: 10 }} />
          {title}
        </Link>
      </Navbar>
    );
  }

  if (!breadcrumbs || breadcrumbs.length === 0) {
    return null;
  }

  return (
    <Navbar className={styles.bar} fluid>
      <Breadcrumb className={styles.list}>
        {breadcrumbs.map((item, i) => {
          if (i === breadcrumbs.length - 1) {
            return (
              <li key={i} className="active">
                {item.badge && (
                  <Label className={styles.badge}>{item.badge}</Label>
                )}
                {item.name}
              </li>
            );
          }

          if (item.link) {
            return (
              <li key={i}>
                <Link to={item.link}>{item.name}</Link>
              </li>
            );
          }

          return <li key={i}>{item.name}</li>;
        })}
      </Breadcrumb>
    </Navbar>
  );
}

export default BreadCrumbs;
