/* eslint-disable react/jsx-no-target-blank */
import React from 'react';
import PropTypes from 'prop-types';
import { globalHistory } from '@reach/router';
import { prettyTracker } from '~helpers/getters';
import { setCookie } from '~helpers/cookies';
import { getTrackingAPIParams } from '~helpers/tracker';

const PrettyLink = ({
  operator,
  pageTemplate,
  module,
  tracker,
  clickedElement,
  className,
  children,
  rel = 'nofollow noreferrer sponsored',
}) => {
  const prettyLink = prettyTracker(operator, tracker, false, pageTemplate);
  const referer = typeof document !== 'undefined' && document?.referrer ? document.referrer : '';

  const onCTAClick = () => {
    // eslint-disable-next-line no-unused-expressions
    process.env.IS_TRACKING_SSR &&
      setCookie(
        'affObject',
        JSON.stringify(
          getTrackingAPIParams(
            pageTemplate,
            module,
            tracker,
            'cta',
            globalHistory.location.href,
            referer
          )
        ),
        1,
        '/'
      );
  };

  return (
    <a
      href={prettyLink || '#'}
      title={operator?.name}
      className={className}
      target="_blank"
      rel={rel}
      aria-label={`${operator?.name} Link`}
      onClick={onCTAClick}
    >
      {children}
    </a>
  );
};

PrettyLink.propTypes = {
  operator: PropTypes.shape({
    name: PropTypes.string,
  }),
  pageTemplate: PropTypes.string,
  module: PropTypes.string,
  tracker: PropTypes.string,
  clickedElement: PropTypes.string,
  className: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node, PropTypes.any]),
  rel: PropTypes.string,
};

export default PrettyLink;
