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

interface UserGroup {
  '@id': string;
  name: string;
  role: string[];
}

@Component({
  selector: 'app-add-user-modal',
  templateUrl: './add-user-modal.component.html',
  styleUrls: ['./add-user-modal.component.css']
})
export class AddUserModalComponent implements OnInit {
  baseUrl: string;
  @Output() userAdded = new EventEmitter<void>();
  @Output() userEdited = new EventEmitter<void>();
  userForm: FormGroup<any>;
  userGroups: UserGroup[] = [];
  organizationalUnits: any[] = [];
  userId: string | null = null;
  loading: boolean = false;
  isEditMode: boolean = false;

  protected views = [
    { value: 'card', name: 'Tarjetas' },
    { value: 'list', name: 'Listado' },
  ];

  constructor(
    public dialogRef: MatDialogRef<AddUserModalComponent>,
    @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.userForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required],
      role: ['', Validators.required],
      groupsView: ['card', Validators.required],
      organizationalUnits: [[]]
    });

    if (data) {
      this.isEditMode = true;
    }
  }

  ngOnInit(): void {
    this.dataService.getUserGroups().subscribe((data) => {
      this.userGroups = data['hydra:member'];
    });

    this.dataService.getOrganizationalUnits().subscribe((data) => {
      this.organizationalUnits = data['hydra:member'].filter((item: any) => item.type === 'organizational-unit');
    });

    if (this.data) {
      this.load();
    } else {
      this.userForm.get('password')?.setValidators([Validators.required]);
    }
  }

  load(): void {
    this.loading = true;
    this.dataService.getUser(this.data).subscribe({
      next: (response) => {
        const organizationalUnitIds = response.allowedOrganizationalUnits.map((unit: any) => unit['@id']);

        this.userForm.patchValue({
          username: response.username,
          role: response.userGroups.length > 0 ? response.userGroups[0]['@id'] : null,
          organizationalUnits: organizationalUnitIds,
          groupsView: response.groupsView
        });

        this.userId = response['@id'];
        this.userForm.get('password')?.clearValidators();
        this.userForm.get('password')?.updateValueAndValidity();
        this.loading = false;
      },
      error: (err) => {
        this.loading = false;
        console.error('Error fetching user:', err);
      }
    });
  }

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

  onSubmit(): void {
    if (this.userForm.valid) {
      const payload: any = {
        username: this.userForm.value.username,
        allowedOrganizationalUnits: this.userForm.value.organizationalUnits,
        enabled: true,
        userGroups: [this.userForm.value.role],
        groupsView: this.userForm.value.groupsView
      };

      if (!this.userId && this.userForm.value.password) {
        payload.password = this.userForm.value.password;
      } else if (this.userId && this.userForm.value.password.trim() !== '') {
        payload.password = this.userForm.value.password;
      }

      this.loading = true;

      if (this.userId) {
        this.http.put(`${this.baseUrl}${this.userId}`, payload).subscribe(
          (response) => {
            this.toastService.success('Usuario editado correctamente');
            this.userEdited.emit();
            this.dialogRef.close();
            this.loading = false;
          },
          (error) => {
            this.toastService.error(error['error']['hydra:description']);
            this.loading = false;
          }
        );
      } else {
        this.http.post(`${this.baseUrl}/users`, payload).subscribe(
          (response) => {
            this.toastService.success('Usuario añadido correctamente');
            this.userAdded.emit();
            this.dialogRef.close();
            this.loading = false;
          },
          (error) => {
            this.toastService.error(error['error']['hydra:description']);
            this.loading = false;
          }
        );
      }
    }
  }
}