import { Component, Inject, OnInit } 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 { NotificationService } from '@shared/ui-api/notification.service';
import { catchError } from 'rxjs/operators';
import { UserGroupsApiService } from '@fleio-api/client-user/user-group/user-groups-api.service';
import { EMPTY } from 'rxjs';
import { UsersApiService } from '@fleio-api/client-user/user/users-api.service';
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-add-user-to-group-dialog',
  templateUrl: './add-user-to-group-dialog.component.html',
  styleUrls: ['./add-user-to-group-dialog.component.scss']
})
export class AddUserToGroupDialogComponent implements IBaseDialog, OnInit {
  associateUserForm = this.formBuilder.group({
    selectedUserGroup: [null, Validators.required]
  });
  dialogTitle = $localize`Select a group and add ${this.data?.user?.email} to it`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Add user to group`,
      primary: true,
      callback: () => this.associateUser(),
    }),
  ];
  dialogForm = this.associateUserForm;
  loading = false;
  selectedUserGroup = this.associateUserForm.controls.selectedUserGroup;

  userGroupSelectedPlaceholder = $localize`User group`;
  userGroupUnselectedPlaceholder = $localize`Select user group ...`;
  userGroupOptionsQueryParams: Record<string, string>;

  constructor(
    public dialogRef: MatDialogRef<AddUserToGroupDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { user: IUserModel },
    private formBuilder: UntypedFormBuilder,
    public userGroupsApiService: UserGroupsApiService,
    private usersApiService: UsersApiService,
    private notificationService: NotificationService,
  ) {
  }

  ngOnInit() {
    this.userGroupOptionsQueryParams = {
      filtering: `users__ne:${this.data?.user?.id}`
    };
  }

  associateUser() {
    this.loading = true;
    this.usersApiService.addToGroup(this.data.user.id, this.selectedUserGroup.value.id).pipe(
      catchError(() => {
        this.notificationService.showMessage($localize`Failed to add user to group`);
        return EMPTY;
      }),
    ).subscribe(() => {
      this.dialogRef.close(true);
    }).add(() => {
      this.loading = false;
    });
  }
}
