import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { ConfigService } from '@shared/config/config.service';
import { IProductModel } from '@fleio-api/billing/model/product.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
import { ProductCyclesApiService } from '@fleio-api/billing/product-cycles/product-cycles-api.service';
import { NavigationEnd, Router } from '@angular/router';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { MatDialog } from '@angular/material/dialog';
import { Observable, Subscription } from 'rxjs';
import { ProductCycleEditFormComponent } from '../../dialogs/product-cycle-edit-form/product-cycle-edit-form.component';

@Component({
  selector: 'app-product-details-overview',
  templateUrl: './product-details-overview.component.html',
  styleUrls: ['./product-details-overview.component.scss']
})
export class ProductDetailsOverviewComponent extends DetailsComponentBase<IProductModel> implements OnInit, OnDestroy {
  displayedColumns: string[] = ['display_name', 'price_model', 'setup_fee', 'is_relative_price', 'status', 'actions'];
  priceHeading: string;
  actions: {
    [key: string]: Array<IAction>;
  } = {};
  routerSubscription: Subscription;

  constructor(
    public config: ConfigService,
    public productCyclesApiService: ProductCyclesApiService,
    public router: Router,
    private matDialog: MatDialog,
  ) {
    super();
    this.routerSubscription = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // needed because on init is not called when navigating to same page
        this.initData();
      }
    });
  }

  initData() {
    if (this.object) {
      if (this.object.price_model === 'dynamic_or_fixed') {
        this.priceHeading = $localize`Minimum price`;
      } else {
        this.priceHeading = $localize`Fixed price`;
      }
      let editCycleTooltip = $localize`Edit cycle`;
      if (this.object.billing_type === 'onetime') {
        editCycleTooltip = $localize`Edit price`;
      }
      let deleteCycleTooltip = $localize`Delete cycle`;
      if (this.object.billing_type === 'onetime') {
        deleteCycleTooltip = $localize`Delete price`;
      }
      for (const cycle of this.object.cycles) {
        this.actions[cycle.id] = [
          new CallbackAction({
            object: this.object,
            tooltip: editCycleTooltip,
            icon: {name: 'edit'},
            name: editCycleTooltip,
            redirectAfterExecute: true,
            redirectUrl: this.config.getPanelUrl(`billing/products/${this.object.id}`),
            callback: () => new Observable<IActionResult>((subscriber) => {
              this.matDialog.open(
                ProductCycleEditFormComponent, {
                  data: {
                    product: this.object,
                    productCycle: cycle,
                  },
                  autoFocus: false,
                }).afterClosed().subscribe(result => {
                subscriber.next({success: !!result, message: null});
                subscriber.complete();
              });
            })
          }),
          new ApiCallAction({
            object: cycle,
            icon: {name: 'delete'},
            tooltip: deleteCycleTooltip,
            name: deleteCycleTooltip,
            confirmOptions: {
              confirm: true,
              title: deleteCycleTooltip,
              message: $localize`Are you sure?`,
            },
            apiService: this.productCyclesApiService,
            callType: CallType.Delete,
            refreshAfterExecute: true,
            redirectAfterExecute: false,
          })
        ];
      }
    }
  }

  ngOnInit() {
    super.ngOnInit();
    this.initData();
    if (this.object?.price_model === 'free') {
      this.displayedColumns = ['display_name', 'status', 'actions'];
    }
    if (this.object?.billing_type === 'onetime') {
      const displayNameIndex = this.displayedColumns.indexOf('display_name');
      this.displayedColumns.splice(displayNameIndex, 1);
    }
  }

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