import { Component, OnDestroy, OnInit } from '@angular/core';
import {
  IRecurringPaymentOptionModel,
  IRecurringPaymentOptionModelResponse
} from '@fleio-api/billing/model/recurring-payment-option.model';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { GatewaysApiService } from '@fleio-api/billing/gateways/gateways-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { map } from 'rxjs/operators';
import { MatDialog } from '@angular/material/dialog';
import { CardEditDialogComponent } from '../../dialogs/card-edit-dialog/card-edit-dialog.component';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';

@Component({
  selector: 'app-recurring-payment-options-details',
  templateUrl: './recurring-payment-options-details.component.html',
  styleUrls: ['./recurring-payment-options-details.component.scss']
})
export class RecurringPaymentOptionsDetailsComponent extends DetailsFormBase<IClientModel>
  implements OnInit, OnDestroy {
  recurringPaymentOptionsResponse: IRecurringPaymentOptionModelResponse;
  recurringPaymentOptions: Array<IRecurringPaymentOptionModel> = [];
  displayedColumns = ['details', 'gateway', 'active', 'actions'];
  recurringOptionsDataSubscription: Subscription;
  deactivateTooltip = $localize`Deactivate`;
  editTooltip = $localize`Edit`;
  reactivateTooltip = $localize`Reactivate`;
  deleteTooltip = $localize`Delete`;
  moveUpTooltip = $localize`Move up`;

  constructor(
    private gatewaysApiService: GatewaysApiService,
    private notificationService: NotificationService,
    private refreshService: RefreshService,
    private activatedRoute: ActivatedRoute,
    private matDialog: MatDialog,
  ) {
    super();
  }

  deactivate(gatewayName: string, gatewayID: FleioId, gatewayDataID: FleioId) {
    this.notificationService.confirmDialog(
      {
        title: $localize`Deactivate recurring payments for ${gatewayName}`,
        message: $localize`Are you sure you want to deactivate recurring payments for ${gatewayName}?`
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.gatewaysApiService.deactivateRecurringPaymentOption(gatewayID, gatewayDataID).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Deactivated`);
            this.refreshService.refresh();
          },
          error: () => {
            this.notificationService.showMessage($localize`Could not deactivate recurring payment option.`);
          }
        });
      }
    });
  }

  edit(recurringPaymentOpt) {
    return this.matDialog.open(
      CardEditDialogComponent, {
        data: {
          gatewayID: recurringPaymentOpt.gateway_id,
          gatewayDataID: recurringPaymentOpt.gateway_data_id,
          expMonth: recurringPaymentOpt.card_details.exp_month_display,
          expYear: recurringPaymentOpt.card_details.exp_year_display,
        },
        autoFocus: false,
      }).afterClosed().pipe(map(result => {
        if (result === true) {
          this.refreshService.refresh();
          return {message: $localize`Saved`};
        } else {
          return {message: null};
        }
    })).subscribe();
  }

  delete(recurringPaymentOpt) {
    let message;
    if (recurringPaymentOpt?.card_details?.last4) {
      message = $localize`Are you sure you want to delete card ending in ${recurringPaymentOpt.card_details.last4}?`;
    } else {
      message = $localize`Are you sure you want to delete card?`;
    }
    this.notificationService.confirmDialog(
      {
        title: $localize`Delete card?`,
        message
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.gatewaysApiService.removeCard(
          recurringPaymentOpt.gateway_id,
          recurringPaymentOpt.gateway_data_id
        ).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Removed`);
            this.refreshService.refresh();
          },
          error: (error) => {
            if (error?.error?.detail) {
              this.notificationService.showMessage(error?.error?.detail);
            } else {
              this.notificationService.showMessage($localize`Could not remove card.`);
            }
          }
        });
      }
    });
  }

  reactivate(gatewayName: string, gatewayID: FleioId, gatewayDataID: FleioId) {
    this.notificationService.confirmDialog(
      {
        title: $localize`Reactivate recurring payments for ${gatewayName}`,
        message: $localize`Are you sure you want to reactivate recurring payments for ${gatewayName}?`
      }
    ).subscribe(result => {
      if (result?.button === 'yes') {
        this.gatewaysApiService.reactivateRecurringPaymentOption(gatewayID, gatewayDataID).subscribe({
          next: () => {
            this.notificationService.showMessage($localize`Reactivated`);
            this.refreshService.refresh();
          },
          error: () => {
            this.notificationService.showMessage($localize`Could not reactivate recurring payment option.`);
          }
        });
      }
    });
  }

  moveUp(gatewayID: FleioId, gatewayDataID: FleioId, order) {
    this.gatewaysApiService.changeRecurringPaymentOptionOrder(
      gatewayID, gatewayDataID, order - 1
    ).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Option order updated`);
        this.refreshService.refresh();
      }, error: () => {
        this.notificationService.showMessage($localize`Could not update recurring payment option order.`);
      }
    });
  }

  ngOnInit(): void {
    this.recurringOptionsDataSubscription = this.activatedRoute.data.subscribe(response => {
      this.recurringPaymentOptionsResponse = response.recurring_payment_options;
      if (this.recurringPaymentOptionsResponse) {
        this.recurringPaymentOptions = this.recurringPaymentOptionsResponse.objects;
      }
    });
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.recurringOptionsDataSubscription) {
      this.recurringOptionsDataSubscription.unsubscribe();
      this.recurringOptionsDataSubscription = null;
    }
  }

}
