import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { IRoleModel } from '@fleio-api/client-user/roles/model/role.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { AuthService } from '@shared/auth/auth.service';
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-associate-client-dialog',
  templateUrl: './associate-client-dialog.component.html',
  styleUrls: ['./associate-client-dialog.component.scss']
})
export class AssociateClientDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  associateClientForm = this.formBuilder.group({
    selectedClient: [null, Validators.required],
    roles: [],
  });
  dialogTitle = $localize`Associate user ${this.data?.user?.full_name || this.data?.user?.email} with a client`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Associate client`,
      primary: true,
      callback: () => this.associateClient(),
    }),
  ];
  dialogForm = this.associateClientForm;
  loading = false;

  selectedClient = this.associateClientForm.controls.selectedClient;
  hasClients = false;
  roles: IRoleModel[];
  clientOptionsQueryParams= {
    filtering: `users__id__ne:${this.data?.user?.id}`
  };

  constructor(
    public dialogRef: MatDialogRef<AssociateClientDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { user: IUserModel },
    private formBuilder: UntypedFormBuilder,
    private clientsApi: ClientsApiService,
    private usersApi: UsersApiService,
    public auth: AuthService,
  ) {
  }

  ngOnInit() {
    if (this.data?.user?.id) {
      this.loading = true;
      this.clientsApi.list(this.clientOptionsQueryParams).subscribe(response => {
        this.hasClients = response.objects.length > 0;
        this.loading = false;
      });
      this.associateClientForm.controls.selectedClient.valueChanges.subscribe(value => {
        if (value && value.id) {
          this.loading = true;
          this.clientsApi.getAvailableRoles(value.id).subscribe(roles => {
            if (this.auth.feature('clients&users.roles')) {
              this.roles = roles.roles;
            } else {
              this.roles = roles.roles.filter(role => role.id === roles.default_role_id);
            }
            if (roles.default_role_id) {
              this.associateClientForm.patchValue({roles: [roles.default_role_id]});
            }
            this.loading = false;
          });
        }
      });
    }
  }

  associateClient() {
    const client: IClientModel = this.selectedClient.value;
    const selectedRoles = this.associateClientForm.controls.roles.value || [];
    this.loading = true;
    this.usersApi.associateClient(this.data.user.id, client.id, selectedRoles).subscribe(() => {
      this.dialogRef.close(true);
    }, error => {
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
  }
}
