import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { IRoleModel } from '@fleio-api/client-user/roles/model/role.model';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';

@Component({
  selector: 'app-change-user-roles-dialog',
  templateUrl: './change-user-roles-dialog.component.html',
  styleUrls: ['./change-user-roles-dialog.component.scss']
})
export class ChangeUserRolesDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  changeRolesForm = this.formBuilder.group({
    roles: [[]],
  });
  dialogTitle = $localize`Edit roles for user ${this.data?.user?.full_name} on client ${this.data?.client?.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save roles`,
      primary: true,
      callback: () => this.saveRoles(),
    }),
  ];
  dialogForm = this.changeRolesForm;
  loading = false;
  roles: IRoleModel[];

  constructor(
    public dialogRef: MatDialogRef<ChangeUserRolesDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      user: IUserModel;
      existingRoles: any[];
    },
    private formBuilder: UntypedFormBuilder,
    private clientsApiService: ClientsApiService,
  ) {
  }

  ngOnInit(): void {
    this.loading = true;
    if (this.data?.client?.id) {
      this.clientsApiService.getAvailableRoles(this.data.client.id).subscribe(roles => {
        this.roles = roles.roles;
        const selectedRoles = this.roles.filter(
          role => this.data.existingRoles.find(userRole => userRole.id === role.id)
        ).map(
          role => role.id
        );
        this.changeRolesForm.patchValue({roles: selectedRoles});
      }).add(() => {
        this.loading = false;
      });
    }
  }

  public saveRoles() {
    const value = this.changeRolesForm.value;
    if (value.roles.length === 0) {
      this.formErrors.showError($localize`At least a role should be selected`);
      return;
    }
    this.loading = true;
    this.clientsApiService.updateRoles(this.data.client.id, this.data.user.id, value.roles,).subscribe(() => {
      this.dialogRef.close(true);
    }, error => {
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
