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

@Component({
  selector: 'app-create-pxe-template',
  templateUrl: './create-pxe-template.component.html',
  styleUrls: ['./create-pxe-template.component.css']
})
export class CreatePxeTemplateComponent implements OnInit {
  baseUrl: string;
  templateForm!: FormGroup;
  previewContent: string = '';
  isEditMode: boolean = false;
  clients: any[] = [];

  templateModels = {
    ogLive: `#!ipxe
set timeout 0
set timeout-style hidden
set ISODIR __OGLIVE__
set default 0
set kernelargs __INFOHOST__
:try_iso
kernel http://__SERVERIP__/tftpboot/\${ISODIR}/ogvmlinuz \${kernelargs} || goto fallback
initrd http://__SERVERIP__/tftpboot/\${ISODIR}/oginitrd.img
boot

:fallback
set ISODIR ogLive
kernel http://__SERVERIP__/tftpboot/\${ISODIR}/ogvmlinuz \${kernelargs}
initrd http://__SERVERIP__/tftpboot/\${ISODIR}/oginitrd.img
boot`,

    disco: `#!ipxe

iseq \${platform} efi && goto uefi_boot || goto bios_boot

:bios_boot
echo "Running in BIOS mode - Booting first disk"
chain http://__SERVERIP__/tftpboot/grub.exe --config-file="title FirstHardDisk;chainloader (hd0)+1;rootnoverify (hd0);boot" || echo "Failed to boot in BIOS mode"
exit

:uefi_boot
echo "Running in UEFI mode - Booting first disk"
sanboot --no-describe --drive 0 --filename \\EFI\\grub\\Boot\\grubx64.efi || echo "Failed to boot in UEFI mode"
exit`
  };

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

  ngOnInit() {
    this.isEditMode = !!this.data;

    if (this.isEditMode) {
      this.getPxeClients();
    }

    this.templateForm = this.fb.group({
      name: [this.data?.name || '', Validators.required],
      templateContent: [this.data?.templateContent || '', Validators.required]
    });
  }

  onSave(): void {
    if (this.isEditMode) {
      this.updatePxeTemplate();
    } else {
      this.createPxeTemplate();
    }
  }

  getPxeClients(): void {
    this.http.get<any>(`${this.baseUrl}/clients?template.id=${this.data.id}`).subscribe({
      next: data => {
        this.clients = data['hydra:member'];
      },
      error: error => {
        console.error('Error al obtener los clientes PXE:', error);
      }
    });
  }

  createPxeTemplate(): void {
    const formValues = this.templateForm.value;
    const payload = {
      name: formValues.name,
      templateContent: formValues.templateContent
    };

    this.http.post<any>(`${this.baseUrl}/pxe-templates`, payload).subscribe({
      next: data => {
        this.toastService.success('Plantilla PXE creada exitosamente');
        this.dialogRef.close(true);
      },
      error: error => {
        this.toastService.error(error.error['hydra:description']);
      }
    });
  }

  updatePxeTemplate(): void {
    const formValues = this.templateForm.value;
    const payload = {
      name: formValues.name,
      templateContent: formValues.templateContent
    };

    this.http.patch<any>(`${this.baseUrl}/pxe-templates/${this.data.uuid}`, payload).subscribe({
      next: data => {
        this.toastService.success('Plantilla PXE actualizada exitosamente');
        this.dialogRef.close(true);
      },
      error: error => {
        this.toastService.error('Error al actualizar la plantilla PXE');
        this.dialogRef.close(false);
      }
    });
  }

  loadTemplateModel(type: 'ogLive' | 'disco'): void {
    const selectedContent = this.templateModels[type];
    this.templateForm.get('templateContent')?.setValue(selectedContent);
    this.toastService.info(`Plantilla ${type} cargada.`);
  }

  addClientToTemplate(client: any): void {
    const postData = {
      client: client['@id']
    };

    this.http.post(`${this.baseUrl}/pxe-templates/${this.data.uuid}/sync-client`, postData).subscribe(
      () => {
        this.toastService.success('Clientes asignados correctamente');
      },
      error => {
        this.toastService.error(error.error['hydra:description']);
      }
    );
  }

  deleteClient(client: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: client.name }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.http.post(`${this.baseUrl}/pxe-templates/${this.data.uuid}/delete-client`, { client: client['@id'] }).subscribe({
          next: () => {
            this.toastService.success('Cliente eliminado exitosamente');
            this.dialogRef.close();
          },
          error: error => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
      }
    });
  }

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