import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientGroupModel } from '@fleio-api/client-user/model/client-group.model';
import { ConfigService } from '@shared/config/config.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { map } from 'rxjs/operators';
import { UntypedFormBuilder } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { AutocompleteHelper } from '@shared/ui-api/helpers/autocomplete-helper';

@Component({
  selector: 'app-client-group-details-overview',
  templateUrl: './client-group-details-overview.component.html',
  styleUrls: ['./client-group-details-overview.component.scss']
})
export class ClientGroupDetailsOverviewComponent extends DetailsComponentBase<IClientGroupModel> implements OnInit {
  clients: IClientModel[];
  clientActions: { [id: number]: IAction };
  displayedColumns = ['id', 'name', '(actions)'];
  currentPage = 1;
  nextPage = false;
  previousPage = false;
  loading = false;

  clientForm = this.formBuilder.group({
    client: [''],
  });


  constructor(
    public config: ConfigService,
    public clientsApiService: ClientsApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
    super();
  }

  ngOnInit() {
    super.ngOnInit();

    if (this.object) {
      this.loadClients(this.currentPage);
    }
  }

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

  loadClients(page: number) {
    this.loading = true;
    this.clientsApiService.getClientsInGroup(this.object.id, page).subscribe(response => {
      this.clients = response.objects;
      this.clientActions = {};
      for (const client of this.clients) {
        this.clientActions[client.id] = this.getClientActions(client);
      }

      this.nextPage = !!response.next;
      this.previousPage = !!response.previous;
      this.loading = false;
    });
  }

  getClientActions(client: IClientModel): IAction[] {
    return [
      new CallbackAction({
        icon: {name: 'link_off'},
        tooltip: $localize`Remove client from group`,
        name: $localize`Remove client from group`,
        displayMessages: false,
        confirmOptions: {
          confirm: true,
          title: $localize`Remove client from group`,
          message: $localize`Are you sure you want to remove client ${client.display} from group?`,
        },
        refreshAfterExecute: true,
        callback: () => this.clientsApiService.removeFromGroup(client.id, this.object.id).pipe(map(() => {
            this.loadClients(this.currentPage);
            AutocompleteHelper.refreshAutocompleteOptions(this.clientForm.controls.client);
            return null;
          }))
      }),
    ];
  }

  addClientToGroup() {
    const client = this.clientForm.controls.client.value as IClientModel;
    this.objectController.loading = true;
    this.clientsApiService.addToGroup(client.id, this.object.id).subscribe(
      (response) => {
        this.loadClients(this.currentPage);
        this.clientForm.get('client').setValue('');
        this.notificationService.showMessage(response.detail);
      },
      () => {
        this.notificationService.showMessage($localize`Failed to add client to group`);
      }
    ).add(() => {
      this.objectController.loading = false;
    });
  }
}
