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

@Component({
  selector: 'app-execute-command-ou',
  templateUrl: './execute-command-ou.component.html',
  styleUrls: ['./execute-command-ou.component.css']
})
export class ExecuteCommandOuComponent implements OnInit {
  form: FormGroup;
  clients: any[] = [];
  commands: any[] = [];
  commandGroups: any[] = [];
  baseUrl: string;

  constructor(
    private dialogRef: MatDialogRef<ExecuteCommandOuComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private http: HttpClient,
    private fb: FormBuilder,
    private configService: ConfigService,
    private toastService: ToastrService,
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.form = this.fb.group({
      selectedCommand: [null],
      selectedCommandGroup: [null],
      clientSelection: [[]]
    });
  }

  ngOnInit(): void {
    this.loadClients();
    this.loadCommands();
    this.loadCommandGroups();
  }

  loadClients(): void {
    this.http.get<any>(`${this.baseUrl}/organizational-units/${this.data.childUnitUuid}`).subscribe(
      response => {
        this.clients = this.getAllClients(response);
        const clientIds = this.clients.map(client => client.uuid);
        this.form.get('clientSelection')?.setValue(clientIds);
      },
      error => console.error('Error al cargar los clientes:', error)
    );
  }

  getAllClients(unit: any): any[] {
    let allClients = unit.clients || [];
    if (unit.children && unit.children.length > 0) {
      unit.children.forEach((child: any) => {
        allClients = allClients.concat(this.getAllClients(child));
      });
    }
    return allClients;
  }

  loadCommands(): void {
    this.http.get<any>(`${this.baseUrl}/commands?page=1&itemsPerPage=30`).subscribe(
      response => {
        this.commands = response['hydra:member'] || [];
      },
      error => this.toastService.error('Error al cargar comandos:', error)
    );
  }

  loadCommandGroups(): void {
    this.http.get<any>(`${this.baseUrl}/command-groups?page=1&itemsPerPage=30`).subscribe(
      response => {
        this.commandGroups = response['hydra:member'] || [];
      },
      error => this.toastService.error('Error al cargar grupos de comandos:', error)
    );
  }

  toggleClientSelection(clientId: string): void {
    const selectedClients = this.form.get('clientSelection')?.value || [];
    if (selectedClients.includes(clientId)) {
      this.form.get('clientSelection')?.setValue(selectedClients.filter((id: string) => id !== clientId));
    } else {
      this.form.get('clientSelection')?.setValue([...selectedClients, clientId]);
    }
  }

  executeCommand(): void {
    const selectedCommandUuid = this.form.get('selectedCommand')?.value || this.form.get('selectedCommandGroup')?.value;
    const isCommandGroup = !!this.form.get('selectedCommandGroup')?.value;

    if (!selectedCommandUuid) {
      console.warn('No se ha seleccionado ningún comando o grupo de comandos');
      return;
    }

    const payload = {
      clients: (this.form.get('clientSelection')?.value || []).map((clientId: string) => `/clients/${clientId}`)
    };

    const url = isCommandGroup
      ? `${this.baseUrl}/command-groups/${selectedCommandUuid}/execute`
      : `${this.baseUrl}/commands/${selectedCommandUuid}/execute`;

    this.http.post(url, payload)
      .subscribe({
        next: () => {
          this.toastService.success('Comando ejecutado con éxito');
          this.dialogRef.close(true);
        },
        error: (error) => {
          this.toastService.error('Error al ejecutar el comando:', error);
          this.dialogRef.close(false);
        }
      });
  }

  closeModal(): void {
    this.dialogRef.close(false);
  }
}
