import * as React from 'react';
import {
  addBranchListener,
  BranchJourney,
  closeBranchJourney,
  removeBranchListener,
  showBranchJourney,
} from './branchUtils';

export const INTERACTION_CONTENT_BRANCH_CTA = 'cta';
export const INTERACTION_CONTENT_BRANCH_DISMISS = 'dismiss';
export const INTERACTION_CONTENT_BRANCH_CONTINUE = 'continue';

export interface BranchUpsellProps {
  delaySecondsUntilUpsell: 0 | 5 | 30 | 120;
  journey: BranchJourney;
  sessionID: string;
  deviceID: string;
  trackEvent: (interactionContent: string) => void;
}

export class BranchUpsell extends React.Component<BranchUpsellProps> {
  private branchTimerHandle: number | undefined;

  public componentDidMount(): void {
    this.branchTimerHandle = window.setTimeout(
      this.openBranch(),
      this.props.delaySecondsUntilUpsell * 1000,
    );
  }

  public componentWillUnmount(): void {
    if (this.branchTimerHandle) {
      window.clearTimeout(this.branchTimerHandle);
    }
    this.closeBranch();
  }

  public render(): null {
    return null;
  }

  public openBranch = () => () => {
    addBranchListener(this.branchEventListener);
    showBranchJourney(
      this.props.journey,
      this.props.sessionID,
      this.props.deviceID,
    );
  };

  public closeBranch = () => {
    removeBranchListener(this.branchEventListener);
    closeBranchJourney();
  };

  public branchEventListener = (event: Branch.BranchJourneyEvent) => {
    let interactionContent;
    switch (event) {
      case 'didClickJourneyCTA':
        interactionContent = INTERACTION_CONTENT_BRANCH_CTA;
        break;
      case 'didClickJourneyClose':
        interactionContent = INTERACTION_CONTENT_BRANCH_DISMISS;
        break;
      case 'didClickJourneyContinue':
        interactionContent = INTERACTION_CONTENT_BRANCH_CONTINUE;
        break;
    }
    if (interactionContent) {
      this.props.trackEvent(interactionContent);
    }
  };
}
