import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { ConfigService } from '@shared/config/config.service';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { IAction } from '@objects-view/interfaces/actions/action';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import {
  ChangeUserRolesDialogComponent
} from '@shared/common-dialogs/clients-users/clients/change-user-roles-dialog/change-user-roles-dialog.component';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IUserProfileDataModel } from '@shared/auth/models/user.model';
import {
  ChangeUserNotificationsSettingsComponent
} from '../../dialogs/change-user-notifications-settings/change-user-notifications-settings.component';
import { UserNotificationsApiService } from '@fleio-api/notifications/user-notifications-api.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import {
  AssociateUserDialogComponent
} from '@shared/common-dialogs/clients-users/clients/associate-user-dialog/associate-user-dialog.component';

@Component({
  selector: 'app-enduser-client-users-tab',
  templateUrl: './enduser-client-users-tab.component.html',
  styleUrls: ['./enduser-client-users-tab.component.scss']
})
export class EnduserClientUsersTabComponent extends DetailsComponentBase<IClientModel> implements OnInit {
  users: IUserModel[];
  displayedColumns: string[] = ['email', 'roles', '(actions)'];
  columnsWithRoles: string[] = ['email', 'roles', '(actions)'];
  columnsWithoutRoles: string[] = ['email', '(actions)'];
  rolesEnabled: boolean;

  usersActions = {};
  currentUser: IUserProfileDataModel;

  constructor(
    private refreshService: RefreshService,
    private clientsApi: ClientsApiService,
    public config: ConfigService,
    private router: Router,
    private matDialog: MatDialog,
    private userNotificationsApiService: UserNotificationsApiService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  ngOnInit() {
    super.ngOnInit();
    this.currentUser = this.config.authService.userData.user;
  }

  protected refreshData() {
    this.refreshService.boost();
    this.rolesEnabled = this.config.authService.feature('clients&users.roles');
    this.displayedColumns = this.rolesEnabled ? this.columnsWithRoles : this.columnsWithoutRoles;
    this.clientsApi.getUsers(this.object.id).subscribe(users => {
      this.users = users.users;
      this.usersActions = {};
      for (const user of this.users) {
        this.usersActions[user.id] = this.getUserActions(user);
      }
    });
  }

  getUserActions(user: any): IAction[] {
    const actions: IAction[] = [];
    if (this.rolesEnabled && !user.invitation) {
      actions.push(
        new CallbackAction({
          object: this.object,
          icon: {name: 'rule'},
          tooltip: $localize`Edit roles`,
          name: $localize`Edit roles`,
          callback: () => this.matDialog.open(
              ChangeUserRolesDialogComponent, {
                data: {client: this.object, user, existingRoles: user.roles},
                autoFocus: false,
              }).afterClosed().pipe(map(result => {
              if (result === false) {
                return;
              }
              this.refreshData();
              return {message: result} as IActionResult;
            }))
        })
      );
    }
    if (!user.invitation) {
      actions.push(
        new CallbackAction({
          object: this.object,
          icon: {name: 'notifications'},
          tooltip: $localize`Edit notifications settings`,
          name: $localize`Edit notifications settings`,
          callback: () => this.matDialog.open(
              ChangeUserNotificationsSettingsComponent, {
                data: {client: this.object, user},
                autoFocus: false,
              }).afterClosed().pipe(map(result => {
              if (result === false) {
                return;
              }
              this.refreshData();
              return {message: result} as IActionResult;
            }))
        })
      );
    }
    actions.push(
      new ApiCallAction({
        icon: {name: user.invitation ? 'delete' : 'link_off'},
        tooltip: user.invitation ? $localize`Delete invite` : $localize`Dissociate user`,
        name: user.invitation ? $localize`Delete invite` : $localize`Dissociate user`,
        confirmOptions: {
          confirm: true,
          title: user.invitation ? $localize`Delete invite` : $localize`Dissociate user`,
          message: user.invitation ?
            $localize`Are you sure you want to delete invitation for user ${user.full_name || user.email}?` :
            $localize`Are you sure you want to dissociate user ${user.full_name || user.email}?`,
        },
        object: this.object,
        apiService: this.clientsApi,
        callType: CallType.Post,
        apiAction: 'dissociate_user',
        apiParams: {
          id: this.object.id,
          relation_id: user.invitation_id,
        },
        postExecuteCallback: () => {
          this.refreshData();
        },
      })
    );

    return actions;
  }

  inviteNewUser() {
    this.userNotificationsApiService.getNotificationsSettings().subscribe(notificationsSettings => {
      this.matDialog.open(
        AssociateUserDialogComponent, {
          data: {
            client: this.object,
            user_invitation: true,
            notificationsSettings,
          },
          autoFocus: false,
        }
      ).afterClosed().subscribe(result => {
        if (result) {
          this.refreshData();
        }
      });
    });
  }
}
