import React from 'react';
// eslint-disable-next-line import/no-extraneous-dependencies
import { Link } from 'gatsby';
import PropTypes from 'prop-types';
import { previewFormat, previewPath, formatPath } from '~helpers/path';

function LinkCustom({
  children = <></>,
  to = '',
  activeClassName = '',
  partiallyActive = false,
  ...other
}) {
  if (!to) {
    return <>{children}</>;
  }

  let preview = false;

  if (typeof window !== 'undefined' && window.location.pathname.includes('/preview')) {
    preview = true;
  }

  return (
    <>
      {preview ? (
        <a
          href={previewFormat(to)}
          {...other}
          onClick={(event) => {
            event.preventDefault();
            window.location = previewPath(to);
          }}
        >
          {children}
        </a>
      ) : (
        <Link
          to={formatPath(to)}
          activeClassName={activeClassName}
          partiallyActive={partiallyActive}
          {...other}
        >
          {children}
        </Link>
      )}
    </>
  );
}

LinkCustom.propTypes = {
  to: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.element, PropTypes.any]),
  activeClassName: PropTypes.string,
  partiallyActive: PropTypes.bool,
  gtmClass: PropTypes.string,
};

export default LinkCustom;
