import * as React from 'react';
import { connect } from 'react-redux';

import { RootState } from 'mweb/common/reducers/root';
import { withTracking, TrackingProps } from 'mweb/common/tracking/withTracking';
import { extendInteractionMedium } from 'mweb/common/tracking/extendInteractionMedium';
import {
  ExperimentNames,
  ExperimentGroups,
} from 'mweb/common/actions/experiments';
import { Experiment, Treatment } from 'mweb/common/containers/experiment';

import { BranchUpsell, BranchUpsellProps } from 'branch-io';

const INTERACTION_MEDIUM_BRANCH = 'branch';

interface BranchUpsellStateProps
  extends Pick<BranchUpsellProps, 'sessionID' | 'deviceID'> {}

interface BranchUpsellOwnProps
  extends Pick<BranchUpsellProps, 'delaySecondsUntilUpsell' | 'journey'> {}

interface BranchUpsellWrappedProps
  extends BranchUpsellOwnProps,
    BranchUpsellStateProps,
    TrackingProps {}

class BranchUpsellWrappedBase extends React.Component<
  BranchUpsellWrappedProps
> {
  render(): JSX.Element {
    return <BranchUpsell {...this.props} trackEvent={this.trackEvent} />;
  }

  private trackEvent = (interactionContent: string) => {
    this.props.trackClick({
      interactionContent,
    })();
  };
}

function mapStateToProps(state: RootState): BranchUpsellStateProps {
  return {
    sessionID: state.device.sessionID,
    deviceID: state.device.deviceID,
  };
}

const BranchUpsellWrapped = connect(mapStateToProps)(
  extendInteractionMedium(
    withTracking(BranchUpsellWrappedBase),
    INTERACTION_MEDIUM_BRANCH,
  ),
) as React.ComponentClass<BranchUpsellOwnProps>;

export class BranchUpsellExperiment extends React.Component<
  BranchUpsellOwnProps
> {
  render(): JSX.Element {
    return (
      <Experiment experimentName={ExperimentNames.Branch}>
        <Treatment group={ExperimentGroups.Treatment}>
          <BranchUpsellWrapped {...this.props} />
        </Treatment>
      </Experiment>
    );
  }
}
