import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { InvoicesApiService } from '@fleio-api/billing/invoices/invoices-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { UntypedFormBuilder } from '@angular/forms';
import { ConfigService } from '@shared/config/config.service';
import { of } from 'rxjs';
import { TimeHelper } from '@shared/ui-api/helpers/time-helper';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';
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';

@Component({
  selector: 'app-invoices-merge-dialog',
  templateUrl: './invoices-merge-dialog.component.html',
  styleUrls: ['./invoices-merge-dialog.component.scss']
})
export class InvoicesMergeDialogComponent implements IBaseDialog, OnInit {
  invoicesToMerge = [];
  invoicesToMergeDisplay = [];
  hasPartiallyPaidInvoices = false;
  newDueDate;
  invoicesMergeForm = this.formBuilder.group({
    override_due_date: [false],
    new_due_date: [null],
    new_due_date_time: [null],
  });
  dialogTitle = $localize`Merge invoices?`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Merge`,
      primary: true,
      callback: () => this.merge(),
    }),
  ];
  dialogForm = this.invoicesMergeForm;
  loading = false;
  timeHelper: TimeHelper;

  constructor(
    public dialogRef: MatDialogRef<InvoicesMergeDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      selectedInvoices: {
        [key: string]: boolean;
      };
    },
    private invoicesApiService: InvoicesApiService,
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
    public config: ConfigService,
  ) {
    this.timeHelper = new TimeHelper(config);
    this.invoicesMergeForm.controls.new_due_date_time.setValidators(
      [ValidatorsHelper.timeValidator(this.timeHelper.timeFormat, this.timeHelper.timeExample)]
    );
  }

  setInvoicesToMergeDisplay() {
    for (const id in this.data.selectedInvoices) {
      if (this.data.selectedInvoices.hasOwnProperty(id)) {
        if (this.data.selectedInvoices[id] === true) {
          this.invoicesToMergeDisplay.push(id);
        }
      }
    }
  }

  setInvoicesToMerge() {
    for (const id in this.data.selectedInvoices) {
      if (this.data.selectedInvoices.hasOwnProperty(id)) {
        if (this.data.selectedInvoices[id] === true) {
          this.invoicesToMerge.push(id);
        }
      }
    }
  }

  ngOnInit() {
    this.setInvoicesToMergeDisplay();
    this.setInvoicesToMerge();
    this.loading = true;
    this.invoicesApiService.mergeOptions(this.invoicesToMerge).subscribe(response => {
      this.hasPartiallyPaidInvoices = response.partially_paid_inv;
      this.newDueDate = response.max_due_date;
    }).add(() => {
      this.loading = false;
    });

    this.invoicesMergeForm.controls.override_due_date.valueChanges.subscribe(value => {
      if (value !== true) {
        this.invoicesMergeForm.controls.new_due_date.setValue(null);
        this.invoicesMergeForm.controls.new_due_date_time.setValue(null);
      }
    });
  }

  merge() {
    if (this.invoicesMergeForm.invalid) {
      return;
    }

    let newDueDate = null;
    if (this.invoicesMergeForm.controls.override_due_date.value) {
      newDueDate = this.invoicesMergeForm.controls.new_due_date.value;
      if (this.timeHelper.processDateFieldTime(newDueDate, this.invoicesMergeForm.controls.new_due_date_time).error) {
        return of(null);
      }
    }

    this.loading = true;
    this.invoicesApiService.merge(
      this.invoicesToMerge,
      newDueDate,
    ).subscribe(() => {
      this.dialogRef.close(true);
    }, error => {
      if (error.error?.new_due_date) {
        this.invoicesMergeForm.controls.new_due_date.setErrors(error.error.new_due_date);
      } else {
        this.notificationService.showMessage($localize`Failed to merge invoices.`);
        this.dialogRef.close(false);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
