import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IYesNoDialogData } from '../interfaces/yes-no-dialog-data';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';

@Component({
  selector: 'app-yes-no-dialog',
  templateUrl: './yes-no-dialog.component.html',
  styleUrls: ['./yes-no-dialog.component.scss']
})
export class YesNoDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors: FormErrorsComponent;

  public loading = false;

  public selectedRadioButton: string;
  dialogTitle = null;
  dialogActions: Array<IAction> = [];

  constructor(
    public dialogRef: MatDialogRef<YesNoDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: IYesNoDialogData,
  ) {
  }

  ngOnInit() {
    this.dialogTitle = this.data?.title;

    if (this.data?.radioButtons?.length) {
      for (const radioButton of this.data.radioButtons) {
        if (radioButton.selected) {
          this.selectedRadioButton = radioButton.id;
        }
      }
    }

    if (!this.data?.hideNoButton) {
      this.dialogActions.push(
        new DialogCallbackAction({
          name: this.data?.noButtonName || $localize`No`,
          primary: false,
          callback: () => this.closeNo(),
        }),
      );
    }
    if (this.data?.secondaryYesButtonName) {
      this.dialogActions.push(
        new DialogCallbackAction({
          name: this.data?.secondaryYesButtonName || $localize`Yes`,
          primary: false,
          callback: () => this.closeYes(true),
        }),
      );
    }
    this.dialogActions.push(
      new DialogCallbackAction({
        name: this.data?.yesButtonName || $localize`Yes`,
        primary: true,
        disabled: this.confirmDisabled(),
        callback: () => this.closeYes(),
      }),
    );
  }

  closeNo() {
    this.dialogRef.close({
      button: 'no',
    } as IYesNoDialogResult);
  }

  flagsChanged() {
    const primaryAction = this.dialogActions.find(action => action.primary === true);
    primaryAction.disabled = this.confirmDisabled();
  }

  confirmDisabled() {
    if (this.data.yesButtonDisabled) {
      return true;
    }
    if (this.data.disableConfirmTillFlagsSelected && Array.isArray(this.data.disableConfirmTillFlagsSelected)) {
      let allFlagsSelected = true;
      let anyFlagSelected = false;
      for (const flag of this.data.flags) {
        if (this.data.disableConfirmTillFlagsSelected.indexOf(flag.id) > -1) {
          if (flag.selected) {
            anyFlagSelected = true;
          } else {
            allFlagsSelected = false;
          }
        }
      }
      if (this.data.disableConfirmTillFlagsSelectedAny) {
        return !anyFlagSelected;
      } else {
        return !allFlagsSelected;
      }
    }

    return this.data.radioButtons && this.data.radioButtons.length && !this.selectedRadioButton;
  }

  closeYes(secondaryYes=false) {
    let dialogResult: IYesNoDialogResult;
    if (this.data.flags?.length || this.data.radioButtons?.length) {
      const flags = {};
      if (this.data.flags?.length) {
        for (const flag of this.data.flags) {
          flags[flag.id] = flag.selected;
        }
      }
      if (this.selectedRadioButton) {
        flags[this.selectedRadioButton] = true;
      }
      dialogResult = {
        button: 'yes',
        flags,
      } as IYesNoDialogResult;

    } else {
      let button = 'yes';
      if (secondaryYes) {
        button += '-secondary';
      }
      dialogResult = {
        button,
      } as IYesNoDialogResult;
    }

    if (this.data.yesAction) {
      this.loading = true;
      this.data.yesAction(dialogResult).subscribe(actionResult => {
        if (actionResult?.success !== false) {
          dialogResult.actionResult = actionResult;
          this.dialogRef.close(dialogResult);
        } else {
          if (actionResult?.message) {
            this.formErrors.showError(actionResult.message);
          }
        }
      }).add(() => {
        this.loading = false;
      })
    } else {
      this.dialogRef.close(dialogResult);
    }
  }

  getWarningMessage(): string {
    if (this.selectedRadioButton && this.data.radioButtons) {
      const selectedFlag = this.data.radioButtons.find(f => f.id === this.selectedRadioButton);
      return selectedFlag?.warningOnSelect || '';
    }

    return '';
  }
}
