import { HttpClient } from '@angular/common/http';
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {DataService} from "../data.service";
import {ToastrService} from "ngx-toastr";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-add-role-modal',
  templateUrl: './add-role-modal.component.html',
  styleUrls: ['./add-role-modal.component.css']
})
export class AddRoleModalComponent {
  roleForm: FormGroup<any>;
  roleId: string | null = null;
  baseUrl: string;

  constructor(
    public dialogRef: MatDialogRef<AddRoleModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private http: HttpClient,
    private fb: FormBuilder,
    private dataService: DataService,
    private toastService: ToastrService,
    private configService: ConfigService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.roleForm = this.fb.group({
      name: ['', Validators.required],
      superAdmin: [false],
      orgAdmin: [false],
      orgOperator: [false],
      orgMinimal: [false],
      userRole: [false],
    });
  }

  ngOnInit(): void {
    if (this.data) {
        this.load()
    }
  }

  load(): void {
    this.dataService.getUserGroup(this.data).subscribe({
      next: (response) => {
        this.roleForm.patchValue({
          name: response.name,
          superAdmin: response.permissions.includes('ROLE_SUPER_ADMIN'),
          orgAdmin: response.permissions.includes('ROLE_ORGANIZATIONAL_UNIT_ADMIN'),
          orgOperator: response.permissions.includes('ROLE_ORGANIZATIONAL_UNIT_OPERATOR'),
          orgMinimal: response.permissions.includes('ROLE_ORGANIZATIONAL_UNIT_MINIMAL'),
          userRole: response.permissions.includes('ROLE_USER'),
        });
        this.roleId = response['@id'];
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
      }
    });
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  onSubmit(): void {
    if (this.roleForm.valid) {
      const formValues = this.roleForm.value;

      const selectedPermissions: string[] = [];
      if (formValues.superAdmin) selectedPermissions.push('ROLE_SUPER_ADMIN');
      if (formValues.orgAdmin) selectedPermissions.push('ROLE_ORGANIZATIONAL_UNIT_ADMIN');
      if (formValues.orgOperator) selectedPermissions.push('ROLE_ORGANIZATIONAL_UNIT_OPERATOR');
      if (formValues.orgMinimal) selectedPermissions.push('ROLE_ORGANIZATIONAL_UNIT_MINIMAL');
      if (formValues.userRole) selectedPermissions.push('ROLE_USER');

      const payload = {
        name: formValues.name,
        permissions: selectedPermissions,
        enabled: true
      };

      if (this.roleId) {
        this.http.put(`${this.baseUrl}${this.roleId}`, payload).subscribe(
          (response) => {
            this.toastService.success('Rol actualizado correctamente');
            this.dialogRef.close();
          },
          (error) => {
            this.toastService.error('Error al editar el rol:', error);
            console.error('Error al editar el rol', error);
          }
        );
      } else {
        this.http.post(`${this.baseUrl}/user-groups`, payload).subscribe(
          (response) => {
            this.toastService.success('Rol añadido correctamente');
            this.dialogRef.close();
          },
          (error) => {
            this.toastService.error('Error al añadir rol:', error);
            console.error('Error al añadir rol', error);
          }
        );
      }
    }
  }

}
