import React, { useContext } from 'react';

import PropTypes from 'prop-types';
import Link from '~hooks/link';

import styles from './breadcrumbs.module.scss';
import keygen from '~helpers/keygen';
import { getHomeBreadcrumbs } from '~helpers/getters';
import { Context } from '~context/MainProvider';

function Breadcrumbs({ page, separator = <span> / </span>, markets }) {
  const { translations } = useContext(Context) || {};
  const activeMarket = markets && markets[page.market];

  if (
    page.path ===
    `${activeMarket && activeMarket.path_prefix ? `${activeMarket.path_prefix}` : '/'}`
  ) {
    return <></>;
  }
  const isPPC = page?.template === 'ppc';

  const home = getHomeBreadcrumbs(page, translations);

  return (
    <ol className={styles.breadcrumbs || ''}>
      <li className={styles.item || ''}>
        {isPPC ? (
          home
        ) : (
          <Link
            to={(activeMarket && activeMarket.path_prefix) || '/'}
            title="Home"
            className="breadcrumbs-gtm"
          >
            {home}
          </Link>
        )}

        {separator}
      </li>
      {page.breadcrumbs &&
        page.breadcrumbs.map((breadcrumb) => (
          <li key={keygen()} className={styles.item}>
            {breadcrumb.path ? (
              <Link to={breadcrumb.path} title={breadcrumb.label} className="breadcrumbs-gtm">
                {breadcrumb.label}
              </Link>
            ) : (
              breadcrumb.label
            )}
            {separator}
          </li>
        ))}
      <li className={styles.item || ''}>{page.vanity_label ? page.vanity_label : page.title}</li>
    </ol>
  );
}

Breadcrumbs.propTypes = {
  markets: PropTypes.shape({
    path_prefix: PropTypes.string,
  }),
  page: PropTypes.shape({
    market: PropTypes.string,
    title: PropTypes.string,
    path: PropTypes.string,
    breadcrumbs: PropTypes.arrayOf(PropTypes.shape({})),
    vanity_label: PropTypes.string,
    translations: PropTypes.shape({}),
    template: PropTypes.string,
    type: PropTypes.string,
    categories: PropTypes.arrayOf({
      short_name: PropTypes.string,
    }),
  }).isRequired,
  separator: PropTypes.element,
};

export default Breadcrumbs;
