import { Component, inject, OnInit, signal } from '@angular/core';
import { FormGroup, FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import SharedModule from 'app/shared/shared.module';
import { LANGUAGES } from 'app/config/language.constants';
import { IUser } from '../user-management.model';
import { UserManagementService } from '../service/user-management.service';
import { ISecurityGroup } from 'app/security/security-group/security-group.model';
import { SecurityGroupService } from 'app/security/security-group/service/security-group.service';
import { map } from 'rxjs';
import { HttpResponse } from '@angular/common/http';

const userTemplate = {} as IUser;

const newUser: IUser = {
  langKey: 'pt-pt',
  activated: true,
} as IUser;

@Component({
  standalone: true,
  selector: 'jhi-user-mgmt-update',
  templateUrl: './user-management-update.component.html',
  imports: [SharedModule, FormsModule, ReactiveFormsModule],
})
export default class UserManagementUpdateComponent implements OnInit {
  languages = LANGUAGES;
  authorities = signal<string[]>([]);
  isSaving = signal(false);

  sharedSecurityGroupCollection: ISecurityGroup[] = [];

  editForm = new FormGroup({
    id: new FormControl(userTemplate.id),
    login: new FormControl(userTemplate.login, {
      nonNullable: true,
      validators: [
        Validators.required,
        Validators.minLength(1),
        Validators.maxLength(50),
        Validators.pattern('^[a-zA-Z0-9!$&*+=?^_`{|}~.-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$|^[_.@A-Za-z0-9-]+$'),
      ],
    }),
    firstName: new FormControl(userTemplate.firstName, { validators: [Validators.maxLength(50)] }),
    lastName: new FormControl(userTemplate.lastName, { validators: [Validators.maxLength(50)] }),
    email: new FormControl(userTemplate.email, {
      nonNullable: true,
      validators: [Validators.minLength(5), Validators.maxLength(254), Validators.email],
    }),
    activated: new FormControl(userTemplate.activated, { nonNullable: true }),
    langKey: new FormControl(userTemplate.langKey, { nonNullable: true }),
    authorities: new FormControl(userTemplate.authorities, { nonNullable: true }),
    securityGroup: new FormControl(userTemplate.securityGroup, { nonNullable: true }),
    allowSamlAuthentication: new FormControl(userTemplate.allowSamlAuthentication, { nonNullable: true }),
    allowUserPwdAuthentication: new FormControl(userTemplate.allowUserPwdAuthentication, { nonNullable: true }),
  });

  private userService = inject(UserManagementService);
  private securityGroupService = inject(SecurityGroupService);
  private route = inject(ActivatedRoute);

  compareSecurityGroup = (o1: ISecurityGroup | null, o2: ISecurityGroup | null): boolean =>
    this.securityGroupService.compareEntity(o1, o2);

  ngOnInit(): void {
    this.route.data.subscribe(({ user }) => {
      if (user) {
        this.editForm.reset(user);
      } else {
        this.editForm.reset(newUser);
      }
    });
    this.userService.authorities().subscribe(authorities => this.authorities.set(authorities));
    this.loadSecurityGroups();
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving.set(true);
    const user = this.editForm.getRawValue();
    if (user.id !== null) {
      this.userService.update(user).subscribe({
        next: () => this.onSaveSuccess(),
        error: () => this.onSaveError(),
      });
    } else {
      this.userService.create(user).subscribe({
        next: () => this.onSaveSuccess(),
        error: () => this.onSaveError(),
      });
    }
  }

  private onSaveSuccess(): void {
    this.isSaving.set(false);
    this.previousState();
  }

  private onSaveError(): void {
    this.isSaving.set(false);
  }

  private loadSecurityGroups(): void {
    this.securityGroupService
      .query()
      .pipe(map((res: HttpResponse<ISecurityGroup[]>) => res.body ?? []))
      .subscribe((groups: ISecurityGroup[]) => (this.sharedSecurityGroupCollection = groups));
  }
}
