import React from 'react';
import PropTypes from 'prop-types';
import { prettyTracker } from '~helpers/getters';
import { setCookie } from '~helpers/cookies';
import { getTrackingAPIParams } from '~helpers/tracker';

const PrettyLink = ({
  operator,
  pageTemplate,
  module,
  tracker,
  clickedElement,
  className,
  children,
}) => {
  const prettyLink = prettyTracker(operator, tracker, false, pageTemplate);
  const url = typeof window !== 'undefined' ? window.location.href : '';
  const onCTAClick = () => {
    // eslint-disable-next-line no-unused-expressions
    process.env.IS_TRACKING_SSR &&
      setCookie(
        'affObject',
        JSON.stringify(getTrackingAPIParams(pageTemplate, module, tracker, clickedElement, url))
      );
  };

  return (
    <a
      href={prettyLink || '#'}
      title={operator.name}
      className={className}
      target="_blank"
      rel="noreferrer sponsored nofollow"
      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]),
};

export default PrettyLink;
