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

@Component({
  selector: 'app-pxe-boot-files',
  templateUrl: './pxe-boot-files.component.html',
  styleUrls: ['./pxe-boot-files.component.css']
})
export class PxeBootFilesComponent implements OnInit {
  baseUrl: string;

  availableOrganizationalUnits: any[] = [];
  selectedUnitChildren: any[] = [];
  dataSource: any[] = [];
  taskForm: FormGroup;
  units: any[] = [];
  ogLiveOptions: any[] = [];
  globalOgLive: string | null = null;
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 0;
  pageSizeOptions: number[] = [5, 10, 20, 40, 100];
  filters: any = {};
  displayedColumns: string[] = ['id', 'ip', 'mac', 'name', 'ogLive'];


  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    private toastService: ToastrService,
    private configService: ConfigService,
    private joyrideService: JoyrideService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.taskForm = this.fb.group({
      organizationalUnit: ['', Validators.required],
      selectedChild: ['', Validators.required]
    });
  }

  ngOnInit(): void {
    this.fetchPxeTemplates();
    this.loadUnits()
  }

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

  fetchPxeTemplates(): void {
    this.http.get<any>(`${this.baseUrl}/pxe-templates?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`, { params: this.filters })
      .subscribe(
        response => {
          this.ogLiveOptions = response['hydra:member'];
          this.length = response['hydra:totalItems'];
        },
        error => {
          this.toastService.error('Error al cargar las plantillas');
        }
      );
  }

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

  applyToAll(): void {
    this.dataSource = this.dataSource.map(client => ({
      ...client,
      ogLive: this.globalOgLive || client.ogLive
    }));
  }

  saveOgLiveTemplates(): void {
    const groupedByTemplate: { [key: string]: string[] } = {};

    this.dataSource.forEach(client => {
      if (client.ogLive) {
        if (!groupedByTemplate[client.ogLive]) {
          groupedByTemplate[client.ogLive] = [];
        }
        groupedByTemplate[client.ogLive].push(client['@id']);
      }
    });

    Object.keys(groupedByTemplate).forEach(templateId => {
      const clients = groupedByTemplate[templateId];
      const url = `${this.baseUrl}${templateId}/add-clients`;

      const payload = {
        clients: clients
      };

      this.http.post(url, payload).subscribe({
        next: () => {
          this.toastService.success(`Clientes guardados correctamente para la plantilla ${templateId}`);
        },
        error: () => {
          this.toastService.error(`Error al guardar clientes para la plantilla ${templateId}`);
        }
      });
    });
  }

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'titleStep',
        'selectUnitStep',
        'selectClassStep',
        'applyToAllStep',
        'saveButtonStep',
        'tableStep',
        'selectTemplateStep'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }

}
