import { addEventListener, ReportBI, withoutDefaults } from '@wix/bex-core'; // withoutDefaults
import { SettingsPageState } from './SettingsPageState';
import { FieldValues } from 'react-hook-form';
import { action } from 'mobx';
import {
  cairoTryAgainClicked,
  cairoApiRequestDataLoadEnd,
  cairoPageCtaClicked,
  cairoPageDiscardChangesBeforeSave,
  loadStart,
  loadEnd,
} from '@wix/bex-core/bi';

export interface SettingsPageStateBIReporterParams<
  T,
  V extends FieldValues = FieldValues,
> {
  reportBI: ReportBI;
  settingsPageState: SettingsPageState<T, V>;
}

export class SettingsPageStateBIReporter<T, V extends FieldValues> {
  readonly settingsPageState: SettingsPageState<T, V>;
  readonly reportBI: ReportBI;
  appLoaded?: () => void;

  constructor(params: SettingsPageStateBIReporterParams<T, V>) {
    this.settingsPageState = params.settingsPageState;
    this.reportBI = params.reportBI;
  }

  _getErrorType(e: any) {
    const isNetworkError = e?.code === 'ERR_NETWORK';
    return isNetworkError ? 'Network error' : 'Technical issue';
  }

  init() {
    const { events } = this.settingsPageState;
    const startTime = performance.now();
    const disposers = [
      addEventListener(
        events,
        'save',
        action(() => {
          events.once('saveError', (err) => {
            this.reportSaveError(err, startTime);
          });
        }),
      ),
      (this.appLoaded = this.reportOnLoadStart(startTime)),
    ];

    return () => {
      disposers.forEach((disposer) => disposer());
    };
  }

  reportButtonClick({
    ctaName,
    isValid,
  }: {
    ctaName: string;
    isValid?: boolean;
  }) {
    this.reportBI(
      withoutDefaults(cairoPageCtaClicked)({
        ctaName,
        ctaType: 'Main',
        location: 'Settings page header',
        isValid,
      }),
    );
  }

  reportSaveTryAgain() {
    this.reportBI(
      withoutDefaults(cairoTryAgainClicked)({
        actionName: 'Saving Settings',
        loaction: 'toast',
      }),
    );
  }

  reportSaveError(e: any, startTime: number) {
    this.reportBI(
      withoutDefaults(cairoApiRequestDataLoadEnd)({
        errorType: this._getErrorType(e),
        duration: performance.now() - startTime,
      }),
    );
  }

  reportOnBeforeUnload() {
    const values = this.settingsPageState.form.getValues();
    const fields = Object.keys(values);
    this.reportBI(
      withoutDefaults(cairoPageDiscardChangesBeforeSave)({
        numOfFields: fields.length,
        numOfActions: fields.reduce(
          (prev, key: any) =>
            prev + +this.settingsPageState.form.getFieldState(key)?.isDirty,
          0,
        ),
      }),
    );
  }

  reportOnLoadStart(startTime: number) {
    this.reportBI(
      withoutDefaults(loadStart)({
        ...this._commonDynamicBiParams(),
      }),
    );
    return () => {
      this.reportOnLoadEnd(Math.round(performance.now() - startTime));
    };
  }

  reportOnLoadEnd(endTime: number) {
    this.reportBI(
      withoutDefaults(loadEnd)({
        ...this._commonDynamicBiParams(),
        loadingTime: endTime,
      }),
    );
  }

  _commonDynamicBiParams() {
    return {
      route: window.location.pathname,
      url: window.location.href,
    };
  }
}
