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

@Component({
  selector: 'app-detail-command-group',
  templateUrl: './detail-command-group.component.html',
  styleUrls: ['./detail-command-group.component.css']
})
export class DetailCommandGroupComponent implements OnInit {
  baseUrl: string;
  form!: FormGroup;
  clients: any[] = [];
  showClientSelect = false;
  canExecute = false;
  loading: boolean = false;

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any,
    private dialogRef: MatDialogRef<DetailCommandGroupComponent>,
    private fb: FormBuilder,
    private configService: ConfigService,
    private http: HttpClient,
    private toastService: ToastrService
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    this.form = this.fb.group({
      selectedClients: [[], Validators.required],
    });

    this.loadClients();
  }

  loadClients(): void {
    this.loading = true;
    this.http.get<any>(`${this.baseUrl}/clients?page=1&itemsPerPage=30`).subscribe({
      next: (response) => {
        this.clients = response['hydra:member'];
        this.loading = false;
      },
      error: (error) => {
        console.error('Error fetching clients:', error);
        this.loading = false;
      }
    });
  }

  toggleClientSelect(): void {
    if (!this.showClientSelect) {
      this.showClientSelect = true;
    } else {
      this.execute();
    }
  }

  execute(): void {
    if (this.form.get('selectedClients')?.value.length > 0) {
      const payload = {
        clients: this.form.value.selectedClients.map((uuid: any) => `/clients/${uuid}`)
      };

      const apiUrl = `${this.baseUrl}/command-groups/${this.data.uuid}/execute`;
      this.loading = true;
      this.http.post(apiUrl, payload).subscribe({
        next: () => {
          this.dialogRef.close();
          this.toastService.success('Grupo de comandos ejecutado exitosamente');
          this.loading = false;
        },
        error: (error) => {
          console.error('Error ejecutando grupo de comandos:', error);
          this.loading = false;
        }
      });
    } else {
      this.form.get('selectedClients')?.markAsTouched();
    }
  }

  onClientSelectionChange(event: any): void {
    this.canExecute = this.form.get('selectedClients')?.value.length > 0;
  }

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