import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IPricingPlanModel } from '@fleio-api/openstack/model/pricing-plan.model';
import { ConfigService } from '@shared/config/config.service';
import { of, Subscription } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.service';
import { PricingRulesApiService } from '@fleio-api/openstack/pricing-rule/pricing-rules-api.service';
import { ActivatedRoute, Router } from '@angular/router';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';
import { AuthService } from '@shared/auth/auth.service';

@Component({
  selector: 'app-pricing-plan-details-overview',
  templateUrl: './pricing-plan-details-overview.component.html',
  styleUrls: ['./pricing-plan-details-overview.component.scss']
})
export class PricingPlanDetailsOverviewComponent extends DetailsComponentBase<IPricingPlanModel> implements OnInit, OnDestroy {
  displayedColumns: string[] = ['display_name', 'resource_name', 'price', 'start_dt', 'end_dt', 'actions'];
  breakpointSubscription: Subscription;
  priceRuleActions: Record<FleioId, Array<IAction>> = {};
  maxVisibleActions = 2;

  constructor(public config: ConfigService, private notificationService: NotificationService,
              private pricingRulesApiService: PricingRulesApiService, private router: Router,
              private route: ActivatedRoute, private refreshService: RefreshService,
              public auth: AuthService,) {
    super();
  }

  ngOnInit(refreshTimerInterval?: number) {
    super.ngOnInit(refreshTimerInterval);
    if (this.object?.pricing_rules?.length) {
      for (const rule of this.object.pricing_rules) {
        this.priceRuleActions[rule.id] = this.getPricingRuleActions(rule);
      }
    }
    if (this.config.appBreakpointObservable) {
      this.breakpointSubscription = this.config.appBreakpointObservable.subscribe(breakpoint => {
        if (breakpoint === 'xs') {
          this.maxVisibleActions = 0;
        } else {
          this.maxVisibleActions = 2;
        }
      });
    }
  }

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

  private getPricingRuleActions(rule): Array<IAction> {
    return [
      new RouterLinkAction({
          icon: {name: 'edit', class: 'fl-icons'},
          name: $localize`Edit pricing rule`,
          tooltip: $localize`Edit pricing rule`,
          routerUrl: this.config.getPanelUrl(
            'settings/openstack-plans/' + rule.id + '/edit-rule'
          ),
          router: this.router,
        }
      ),
      new CallbackAction(
        {
          object: rule,
          icon: {name: 'delete'},
          name: $localize`Delete pricing rule`,
          tooltip: $localize`Delete pricing rule`,
          callback: () => {
            this.deletePricingRule(rule.id);
            return of(null);
          },
        }
      )
    ];
  }

  public deletePricingRule(id) {
    const dialogResult$ = this.notificationService.confirmDialog({
      title: $localize`Delete pricing rule?`,
      message: $localize`Deleting the pricing rule will apply to all calculated costs`,
    });
    dialogResult$.subscribe(dialogResult => {
      if (dialogResult?.button === 'yes') {
        this.pricingRulesApiService.delete(id).subscribe({
            next: () => {
              this.notificationService.showMessage($localize`Successfully deleted price rule.`);
              if (this.priceRuleActions && this.priceRuleActions.hasOwnProperty(id)) {
                delete this.priceRuleActions[id];
              }
              this.refreshService.refresh();
            },
            error: () => {
              this.notificationService.showMessage($localize`Could not delete price rule.`);
            }
          }
        );
      }
    });
  }
}
