import { Component, OnInit, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';
import { FormControl } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { OperationResultDialogComponent } from "../operation-result-dialog/operation-result-dialog.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-add-clients-to-subnet',
  templateUrl: './add-clients-to-subnet.component.html',
  styleUrls: ['./add-clients-to-subnet.component.css']
})
export class AddClientsToSubnetComponent implements OnInit {
  baseUrl: string;
  units: any[] = [];
  clients: any[] = [];
  selectedClients: string[] = [];
  loading: boolean = true;
  unitControl = new FormControl();
  childUnitControl = new FormControl();
  allSelected: boolean = false;

  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<AddClientsToSubnetComponent>,
    private toastService: ToastrService,
    public dialog: MatDialog,
    private configService: ConfigService,
    @Inject(MAT_DIALOG_DATA) public data: { subnetUuid: string, subnetName: string }
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    this.loading = true;
    this.loadUnits();
  }

  loadUnits() {
    this.http.get<any>(`${this.baseUrl}/organizational-units?page=1&itemsPerPage=500`).subscribe(
      response => {
        this.units = response['hydra:member'];
        this.loading = false;
      },
      error => console.error('Error fetching organizational units:', error)
    );
  }

  loadChildUnits(event: any) {
    this.http.get<any>(`${this.baseUrl}/clients?organizationalUnit.id=${event.value.id}&exists[subnet]=false`).subscribe(
      response => {
        this.clients = response['hydra:member'];
      },
      error => console.error('Error fetching child units:', error)
    );
  }

  save() {
    this.loading = true;
    const postData = { clients: this.selectedClients.map(clientId => `/clients/${clientId}`) };

    this.http.post(`${this.baseUrl}/og-dhcp/server/${this.data.subnetUuid}/post-host`, postData).subscribe(
      (response: any) => {
        this.dialog.open(OperationResultDialogComponent, {
          width: '800px',
          data: {
            success: response.success || [],
            errors: response.errors || []
          }
        });

        this.loading = false;
        this.dialogRef.close(this.selectedClients);
      },
      error => {
        this.toastService.error(`Error al asignar el cliente: ${error.error['hydra:description']}`);
      }
    );
  }

  toggleSelectAll() {
    if (this.allSelected) {
      this.selectedClients = [];
    } else {
      this.selectedClients = this.clients.map(client => client.uuid);
    }
    this.allSelected = !this.allSelected;
  }

  toggleClientSelection(uuid: string) {
    const index = this.selectedClients.indexOf(uuid);
    if (index === -1) {
      this.selectedClients.push(uuid);
    } else {
      this.selectedClients.splice(index, 1);
    }

    this.allSelected = this.selectedClients.length === this.clients.length;
  }

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