import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormArray, UntypedFormBuilder } from '@angular/forms';
import { ConfigService } from '@shared/config/config.service';
import { Router } from '@angular/router';
import {
  TicketStaffNotificationsSettingsApiService
} from '@fleio-api/plugins/tickets/ticket-staff-notifications-settings-api.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { EMPTY, Observable, of, Subscription } from 'rxjs';
import { IPluginComponent } from '@shared/plugins/interfaces/plugin-component';
import { FleioId } from '@fleio-api/base-model/base-fleio-object.model';

@Component({
  selector: 'app-user-ticket-notifications-settings-form',
  templateUrl: './user-ticket-notifications-settings-form.component.html',
  styleUrls: ['./user-ticket-notifications-settings-form.component.scss']
})
export class UserTicketNotificationsSettingsFormComponent extends DetailsFormBase<any> implements OnInit, IPluginComponent, OnDestroy {
  notificationsSettingsForm = this.formBuilder.group({
    settings: this.formBuilder.array([])
  });
  staffNotificationsSettings = this.notificationsSettingsForm.controls.settings as UntypedFormArray;
  data: {
    observableUserSave: Observable<FleioId>;
    userID: FleioId;
    onUserForm: boolean;
    onUserSave: (router: Router, config: ConfigService) => void;
  };
  userSaveSubscription: Subscription;
  appBreakpointSubscription: Subscription;
  appBreakpoint: string;

  constructor(
    private formBuilder: UntypedFormBuilder,
    public config: ConfigService,
    private router: Router,
    private ticketStaffNotificationsSettingsApiService: TicketStaffNotificationsSettingsApiService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  ngOnInit(): void {
    if (this.objectController) {
      this.objectController.actionCallback = (action: IAction) => this.saveSettings(action);
    }
    if (this.data?.onUserForm) {
      // init data for user edit page
      this.ticketStaffNotificationsSettingsApiService.permissions().subscribe(permissions => {
        if (permissions['staff_ticket_notifications_settings.get_user_settings'] &&
          permissions['staff_ticket_notifications_settings.save_user_settings']) {
          this.ticketStaffNotificationsSettingsApiService.getUserSettings(this.data.userID).subscribe(response => {
            if (response?.objects) {
              response.objects.forEach(value => {
                this.staffNotificationsSettings.push(this.formBuilder.group(value));
              });
            }
          });
          this.userSaveSubscription = this.data.observableUserSave.subscribe(value => {
            if (value) {
              this.saveSettings(null, value);
            }
          });
        } else {
          this.userSaveSubscription = this.data.observableUserSave.subscribe(value => {
            if (value) {
              this.data.onUserSave(this.router, this.config);
            }
          });
        }
      });
    } else {
      // on "/tickets/notifications-settings", settings are resolved at route level
      super.ngOnInit();  // we want DetailsFormBase functionality only here, don't call super on user edit page
      if (this.object && this.object.objects) {
        this.object.objects.forEach(value => {
          this.staffNotificationsSettings.push(this.formBuilder.group(value));
        });
      }
      if (!this.staffNotificationsSettings || !this.staffNotificationsSettings.length) {
        // no settings because no departments, disable action
        this.primaryAction.disabled = true;
      }
    }
    this.appBreakpointSubscription = this.config.appBreakpointObservable.subscribe(breakpoint => {
      this.appBreakpoint = breakpoint;
    });
  }

  redirectOnSubmit() {
    if (this.data?.onUserForm) {
      this.data.onUserSave(this.router, this.config);
    } else {
      this.router.navigateByUrl(this.config.getPanelUrl('user/profile')).then(() => {});
    }
  }

  saveSettings(action: IAction, userID=null) {
    if (!this.staffNotificationsSettings || !this.staffNotificationsSettings.length) {
      // no settings because no departments, save won't do anything so redirect
      this.redirectOnSubmit();
      return EMPTY;
    }
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }
    const value = this.notificationsSettingsForm.value;
    if (userID) {
      if (this.objectController) {
        this.objectController.loading = true;
      }
      this.ticketStaffNotificationsSettingsApiService.saveUserSettings(value, userID).subscribe({
        next: () => {
          this.redirectOnSubmit();
        },
        error: (error) => {
          if (this.objectController) {
            this.objectController.loading = false;
          }
          if (error.error) {
            this.setErrors(error.error);
          }
        }
      });
    } else {
      this.objectController.loading = true;
      this.ticketStaffNotificationsSettingsApiService.saveCurrentUserSettings(value).subscribe({
        next: () => {
          this.router.navigateByUrl(this.config.getPanelUrl('user/profile')).then(() => {});
        },
        error: (error) => {
          this.objectController.loading = true;
          if (error.error) {
            this.setErrors(error.error);
          }
        }
      });
    }
    return of(null);
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.userSaveSubscription) {
      this.userSaveSubscription.unsubscribe();
      this.userSaveSubscription = null;
    }
    if (this.appBreakpointSubscription) {
      this.appBreakpointSubscription.unsubscribe();
      this.appBreakpointSubscription = null;
    }
  }

}
