import * as React from 'react';
import omit from 'lodash-es/omit';
import { Link, LinkProps } from 'react-router-dom';

import { UITrackingPayload } from 'mweb/common/actions/tracking';
import { withTracking, TrackingProps } from 'mweb/common/tracking/withTracking';

export interface TrackedLinkProps
  extends LinkProps,
    TrackingProps,
    ObjectOmit<
      UITrackingPayload,
      'interactionMedium' | 'interactionTargetPath'
    > {}

export class TrackedLinkBase extends React.PureComponent<TrackedLinkProps, {}> {
  render(): JSX.Element {
    return (
      <Link
        {...omit(this.props, [
          'trackClick', // from TrackingProps
          'interactionContent', // from UITrackingPayload
          'onClick', // from LinkProps
        ]) as LinkProps}
        onClick={this.props.trackClick(
          {
            interactionContent: this.props.interactionContent,
            interactionTargetPath:
              typeof this.props.to === 'string'
                ? this.props.to
                : this.props.to.pathname,
          },
          this.props.onClick,
        )}
      >
        {this.props.children}
      </Link>
    );
  }
}

export const TrackedLink = withTracking(TrackedLinkBase);
