import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } 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 { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
import { IRoleModel } from '@fleio-api/client-user/roles/model/role.model';
import { AuthService } from '@shared/auth/auth.service';
import {
  IUserNotificationSettingsResponseModel
} from '@fleio-api/notifications/model/user-notification-settings-response.model';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';

@Component({
  selector: 'app-associate-user-dialog',
  templateUrl: './associate-user-dialog.component.html',
  styleUrls: ['./associate-user-dialog.component.scss']
})
export class AssociateUserDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  associateUserForm = this.formBuilder.group({
    selectedUser: [null, Validators.required],
    roles: [],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [];
  dialogForm = this.associateUserForm;

  selectedUser = this.associateUserForm.controls.selectedUser;
  roles: IRoleModel[];
  notificationSettingsKeys = [];
  hasUsers = false;
  loading = false;

  userOptionsQueryParams = {
    filtering: `clients__id__ne:${this.data?.client?.id}+is_staff:false+is_active:true`
  };

  constructor(
    public dialogRef: MatDialogRef<AssociateUserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      user_invitation: boolean;
      notificationsSettings: IUserNotificationSettingsResponseModel;
      associatedUsers?: Array<IUserModel>;
    },
    private formBuilder: UntypedFormBuilder,
    private clientsApi: ClientsApiService,
    private usersApi: UsersApiService,
    public auth: AuthService,
  ) {
  }

  ngOnInit() {
    if (this.data?.client?.id) {
      if (this.data.user_invitation) {
        this.dialogTitle = $localize`Invite user for client ${this.data.client?.name}`;
        this.dialogActions.push(
          new DialogCallbackAction({
            name: $localize`Invite user`,
            primary: true,
            callback: () => this.inviteUser(),
          }),
        );
      } else {
        this.dialogTitle = $localize`Associate client ${this.data.client?.name} with a user`;
        this.dialogActions.push(
          new DialogCallbackAction({
            name: $localize`Associate user`,
            primary: true,
            callback: () => this.associateUser(),
          }),
        );
      }
      this.loading = true;
      this.clientsApi.getAvailableRoles(this.data.client.id).subscribe(roles => {
        const rolesEnabled = this.auth.feature('clients&users.roles');
        if (rolesEnabled) {
          this.roles = roles.roles;
        } else {
          this.roles = roles.roles.filter(role => role.id === roles.default_role_id);
        }
        if (roles.default_role_id) {
          this.associateUserForm.patchValue({roles: [roles.default_role_id]});
        }
        if (!rolesEnabled) {
          this.associateUserForm.controls.roles.disable();
        }
      }).add(() => {
        this.loading = false;
      });
    }

    if (this.data.notificationsSettings) {
      for (const key in this.data.notificationsSettings.detail) {
        if (this.data.notificationsSettings.detail.hasOwnProperty(key)) {
          this.notificationSettingsKeys.push(key);
          this.associateUserForm.addControl(key, this.formBuilder.group({
            name: this.formBuilder.control(this.data.notificationsSettings.detail[key].name),
            display_name: this.formBuilder.control(this.data.notificationsSettings.detail[key].display_name),
            enabled: this.formBuilder.control(this.data.notificationsSettings.detail[key].enabled)
          }));
        }
      }
    }

    if (this.data?.client?.id && !this.data.user_invitation) {
      this.loading = true;
      this.usersApi.list(this.userOptionsQueryParams).subscribe(users => {
        this.hasUsers = users.objects.length > 0;
        this.loading = false;
      });
    }
  }

  associateUser() {
    if (this.data.user_invitation) {
      return this.inviteUser();
    }
    const user: IUserModel = this.selectedUser.value;
    const selectedRoles = this.associateUserForm.controls.roles.value || [];
    this.loading = true;
    this.clientsApi.associateUser(this.data.client.id, user.id, selectedRoles).subscribe({
      next: () => {
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  inviteUser() {
    const userEmail: string = this.selectedUser.value;
    const selectedRoles = this.associateUserForm.controls.roles.value || [];
    const selectedNotificationsSettings = [];
    for (const item of this.notificationSettingsKeys) {
      const control = this.associateUserForm.controls[item] as UntypedFormGroup;
      selectedNotificationsSettings.push({
        target_category: item,
        enabled: control.controls.enabled.value,
      });
    }
    this.loading = true;
    this.clientsApi.inviteUser(
      this.data.client.id, userEmail, selectedRoles, selectedNotificationsSettings
    ).subscribe({
      next: () => {
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
