import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { IRegionModel } from '@fleio-api/openstack/model/region.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { NotificationService } from '@shared/ui-api/notification.service';
import { GatewaysApiService } from '@fleio-api/billing/gateways/gateways-api.service';
import { Moment } from 'moment';
import { MatDatepicker } from '@angular/material/datepicker';
import * as _moment from 'moment';
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter } from '@angular/material-moment-adapter';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
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';

const FORMATS = {
  parse: {
    dateInput: 'MM/YYYY',
  },
  display: {
    dateInput: 'MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};

@Component({
  selector: 'app-card-edit-dialog',
  templateUrl: './card-edit-dialog.component.html',
  styleUrls: ['./card-edit-dialog.component.scss'],
  providers: [
    {
      provide: DateAdapter,
      useClass: MomentDateAdapter,
      deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
    },

    {provide: MAT_DATE_FORMATS, useValue: FORMATS},
  ],
})
export class CardEditDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  selectedRegion: IRegionModel;
  cardEditForm = this.formBuilder.group({
    exp: [_moment(), Validators.required],
  });
  dialogTitle = $localize`Edit card data`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save`,
      primary: true,
      callback: () => this.update(),
    }),
  ];
  dialogForm = this.cardEditForm;
  loading = false;
  backendErrors = {};

  constructor(
    public dialogRef: MatDialogRef<CardEditDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      gatewayID: FleioId;
      gatewayDataID: FleioId;
      expMonth;
      expYear;
    },
    private notificationService: NotificationService,
    private formBuilder: UntypedFormBuilder,
    private gatewaysApiService: GatewaysApiService,
  ) {
  }

  public update() {
    if (!this.cardEditForm.valid) {
      return;
    }
    const value = this.cardEditForm.controls.exp.value;
    const expMonth = value.month() + 1;
    const expYear = value.year();
    this.loading = true;
    this.gatewaysApiService.updateCard(
      this.data.gatewayID,
      this.data.gatewayDataID,
      expMonth,
      expYear,
    ).subscribe(() => {
      this.dialogRef.close(true);
    }, error => {
      this.backendErrors = error.error;
      this.formErrors.setBackendErrors(this.backendErrors);
    }).add(() => {
      this.loading = false;
    });
  }

  setMonthAndYear(normalizedMonthAndYear: Moment, datepicker: MatDatepicker<Moment>) {
    let ctrlValue = this.cardEditForm.controls.exp.value;
    if (!ctrlValue) {
      ctrlValue = _moment();
    }
    ctrlValue.month(normalizedMonthAndYear.month());
    ctrlValue.year(normalizedMonthAndYear.year());
    this.cardEditForm.controls.exp.setValue(ctrlValue);
    datepicker.close();
  }

  ngOnInit() {
    this.cardEditForm.controls.exp.setValue(_moment(`${this.data.expMonth}/${this.data.expYear}`, 'MM/YY'));
  }

}
