import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { of } from 'rxjs';
import { NotificationService } from '@shared/ui-api/notification.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-change-user-notifications-settings',
  templateUrl: './change-user-notifications-settings.component.html',
  styleUrls: ['./change-user-notifications-settings.component.scss']
})
export class ChangeUserNotificationsSettingsComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  userNotificationsSettingsForm = new UntypedFormGroup({});
  dialogTitle = $localize`Notifications settings`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save settings`,
      primary: true,
      callback: () => this.save(),
    }),
  ];
  dialogForm = this.userNotificationsSettingsForm;
  loading = false;
  keysList = [];
  userNotificationsSettingsResponse;
  getAllTicketNotificationsTooltip = $localize`Receives all ticket notifications\nfor related client`;

  constructor(
    public dialogRef: MatDialogRef<ChangeUserNotificationsSettingsComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      client: IClientModel;
      user: IUserModel;
    },
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private clientsApiService: ClientsApiService,
  ) {
  }

  ngOnInit(): void {
    this.loading = true;
    const controlsConfig = {};
    if (this.data?.client?.id) {
      this.clientsApiService.getUserNotificationsSettings(
        this.data.client.id, this.data.user.id
      ).subscribe(response => {
        this.userNotificationsSettingsResponse = response;
        for (const key in response.detail) {
          if (response.detail.hasOwnProperty(key)) {
            this.keysList.push(key);
            controlsConfig[key] = this.formBuilder.group({
              name: this.formBuilder.control(response.detail[key].name),
              display_name: this.formBuilder.control(response.detail[key].display_name),
              enabled: this.formBuilder.control(response.detail[key].enabled)
            });
          }
        }
        this.keysList = this.keysList.sort();
        this.userNotificationsSettingsForm = this.formBuilder.group(controlsConfig);
      }).add(() => {
        this.loading = false;
      });
    }
  }

  save() {
    const value = this.userNotificationsSettingsForm.value as any;
    this.loading = true;
    this.clientsApiService.setUserNotificationsSettings(
      this.data.client.id,
      this.data.user.id,
      value
    ).subscribe(() => {
      this.dialogRef.close(true);
    }, error => {
      this.notificationService.showMessage($localize`Failed to update notifications settings`);
      this.formErrors.setBackendErrors(error.error);
    }).add(() => {
      this.loading = false;
    });
    return of(null);
  }
}
