import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IPredefinedReplyCategoryModel } from '@fleio-api/plugins/tickets/model/predefined-reply-category.model';
import { IPredefinedReplyModel } from '@fleio-api/plugins/tickets/model/predefined-reply.model';
import { ConfigService } from '@shared/config/config.service';
import { PredefinedReplyCategoryApiService } from '@fleio-api/plugins/tickets/predefined-reply-category-api.service';
import { Router } from '@angular/router';
import { of } from 'rxjs';
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 { NotificationService } from '@shared/ui-api/notification.service';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';

@Component({
  selector: 'app-predefined-reply-category-details-overview',
  templateUrl: './predefined-reply-category-details-overview.component.html',
  styleUrls: ['./predefined-reply-category-details-overview.component.scss']
})
export class PredefinedReplyCategoryDetailsOverviewComponent extends DetailsFormBase<IPredefinedReplyCategoryModel> implements OnInit {
  predefinedReplies: Array<IPredefinedReplyModel>;
  predefinedRepliesActions = {};
  permissions = {};
  currentPage = 1;
  nextPage = false;
  previousPage = false;
  loading = false;

  constructor(
    public config: ConfigService,
    private predefinedReplyCategoryApiService: PredefinedReplyCategoryApiService,
    private router: Router,
    private notificationService: NotificationService,
  ) {
    super();
  }

  changePage(action: string) {
    if (action === 'next') {
      this.currentPage = this.currentPage + 1;
      this.getPredefinedReplies(this.currentPage);
    }
    if (action === 'previous') {
      this.currentPage = this.currentPage - 1;
      this.getPredefinedReplies(this.currentPage);
    }
  };

  getPredefinedReplies(page: number) {
    this.loading = true;
    this.predefinedReplyCategoryApiService.getPredefinedReplies(this.object.id, page).subscribe(response => {
      this.predefinedReplies = response.objects;
      for (const predefinedReply of this.predefinedReplies) {
        this.predefinedRepliesActions[predefinedReply.id] = this.getPredefinedRepliesActions(predefinedReply);
        predefinedReply.editUrl = this.config.getPanelUrl(
          `tickets/predefined-replies/category/${this.object.id}/edit-reply/${predefinedReply.id}`
        );
      }
      this.nextPage = !!response.next;
      this.previousPage = !!response.previous;
      this.loading = false;
    });
  }

  private getPredefinedRepliesActions(predefinedReply: IPredefinedReplyModel): IAction[] {
    return [
      new RouterLinkAction({
          icon: {name: 'edit', class: 'fl-icons'},
          name: $localize`Edit`,
          tooltip: $localize`Edit`,
          routerUrl: this.config.getPanelUrl(
            `tickets/predefined-replies/category/${this.object.id}/edit-reply/${predefinedReply.id}`
          ),
          router: this.router,
          noPermissions: !this.permissions['predefined_reply_categories.save_predefined_reply'],
        }
      ),
      new CallbackAction(
        {
          object: predefinedReply,
          icon: {name: 'delete'},
          name: $localize`Delete`,
          tooltip: $localize`Delete predefined reply`,
          callback: () => {
            this.notificationService.confirmDialog({
                title: $localize`Delete predefined reply`,
                message: $localize`Are you sure you want to delete predefined reply?`,
              }).subscribe((result: IYesNoDialogResult) => {
              if (result?.button === 'yes') {
                this.predefinedReplyCategoryApiService.deletePredefinedReply(
                  this.object.id, predefinedReply.id
                ).subscribe(() => {
                  this.notificationService.showMessage($localize`Predefined reply deleted`);
                  this.getPredefinedReplies(this.currentPage);
                });
              }
            });
            return of(null);
          },
          noPermissions: !this.permissions['predefined_reply_categories.delete_predefined_reply'],
        }
      )
    ];
  }

  goToAddNewReply() {
    this.router.navigateByUrl(
      this.config.getPanelUrl(`tickets/predefined-replies/category/${this.object.id}/add-reply`)
    );
    return of(null);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.getPredefinedReplies(this.currentPage);
    if (this.objectController) {
      this.objectController.actionCallback = () => this.goToAddNewReply();
      this.permissions = this.objectController?.additionalObjects?.permissions;
    }
  }

}
