import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { CreatePxeTemplateComponent } from './create-pxeTemplate/create-pxe-template.component';
import { MatDialog } from '@angular/material/dialog';
import { MatTableDataSource } from '@angular/material/table';
import { PageEvent } from '@angular/material/paginator';
import { ToastrService } from 'ngx-toastr';
import { DatePipe } from '@angular/common';
import { DataService } from './data.service';
import { ShowTemplateContentComponent } from "./show-template-content/show-template-content.component";
import { Observable } from "rxjs";
import { JoyrideService } from 'ngx-joyride';
import { DeleteModalComponent } from "../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ServerInfoDialogComponent } from "../../ogdhcp/server-info-dialog/server-info-dialog.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-pxe',
  templateUrl: './pxe.component.html',
  styleUrls: ['./pxe.component.css']
})
export class PxeComponent {
  baseUrl: string;
  private apiUrl: string;
  pxeTemplates: any[] = [];
  currentPage: number = 1;
  dataSource = new MatTableDataSource<any>();
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 1;
  pageSizeOptions: number[] = [5, 10, 20, 40, 100];
  selectedElements: string[] = [];
  loading: boolean = false;
  filters: { [key: string]: string } = {};
  alertMessage: string | null = null;
  datePipe: DatePipe = new DatePipe('es-ES');
  selectedItem: any = null;
  previewContent: any | null = null;
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (user: any) => `${user.id}`
    },
    {
      columnDef: 'name',
      header: 'Nombre de la plantilla',
      cell: (user: any) => `${user.name}`
    },
    {
      columnDef: 'synchronized',
      header: 'Sincronizado',
      cell: (user: any) => `${user.synchronized}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (user: any) => `${this.datePipe.transform(user.createdAt, 'dd/MM/yyyy hh:mm:ss')}`
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

  constructor(
    public dialog: MatDialog,
    private http: HttpClient,
    private toastService: ToastrService,
    private dataService: DataService,
    private joyrideService: JoyrideService,
    private configService: ConfigService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/pxe-templates`;
  }

  ngOnInit(): void {
    this.loading = true;
    this.search();
    this.loadAlert()
    this.syncTemplates()
    this.loading = false;
  }

  search(): void {
    this.dataService.getPxeTemplates(this.filters).subscribe(
      data => {
        this.dataSource.data = data;
      },
      error => {
        console.error('Error fetching pxe templates', error);
      }
    );
  }

  addPxeTemplate() {
    const dialogRef = this.dialog.open(CreatePxeTemplateComponent, {
      width: '800px'
    });

    dialogRef.afterClosed().subscribe(() => {
      this.search();
    });
  }


  editPxeTemplate(template: any) {
    const dialogRef = this.dialog.open(CreatePxeTemplateComponent, {
      data: template, // Pasa los datos del template para edición
      width: '800px'
    });

    dialogRef.afterClosed().subscribe(() => {
      this.search();
    });
  }

  toggleAction(image: any, action: string): void {
    switch (action) {
      case 'delete':
        const dialogRef = this.dialog.open(DeleteModalComponent, {
          width: '300px',
          data: { name: image.name }
        });

        dialogRef.afterClosed().subscribe(result => {
          if (result) {
            this.http.post(`${this.apiUrl}/server/${image.uuid}/delete`, {}).subscribe({
              next: () => {
                this.toastService.success('Plantilla eliminada exitosamente');
                this.search();
              },
              error: (error) => {
                console.error('Error al eliminar la subred', error);
                this.toastService.error(error.error['hydra:description']);
              }
            });
          }
        })
        break;
      default:
        console.error('Acción no soportada:', action);
        break;
    }
  }

  showTemplate(event: MouseEvent, data: any): void {
    event.stopPropagation();
    const dialogRef = this.dialog.open(ShowTemplateContentComponent, { data: { data }, width: '700px' });
  }

  syncTemplates() {
    this.http.post(`${this.apiUrl}/sync`, {})
      .subscribe(response => {
        this.toastService.success('Sincronización completada');
        this.search()
      }, error => {
        console.error('Error al sincronizar', error);
        this.toastService.error('Error al sincronizar');
      });
  }

  applyFilter() {
    this.http.get<any>(`${this.apiUrl}?page=${this.page}&itemsPerPage=${this.itemsPerPage}`).subscribe({
      next: (response) => {
        this.dataSource.data = response['hydra:member'];
        this.length = response['hydra:totalItems'];
      },
      error: (error) => {
        console.error('Error al cargar las imágenes:', error);
      }
    });
  }

  loadAlert(): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/server/get-collection`);
  }

  openInfoDialog() {
    this.loadAlert().subscribe(
      response => {
        this.alertMessage = response.message;

        this.dialog.open(ServerInfoDialogComponent, {
          width: '600px',
          data: {
            message: this.alertMessage
          }
        });
      },
      error => {
        this.toastService.error(error.error['hydra:description']);
        console.error('Error al cargar la información del alert', error);
      }
    );
  }

  onPageChange(event: PageEvent) {
    this.page = event.pageIndex;
    this.itemsPerPage = event.pageSize;
    this.applyFilter();
  }

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'serverInfoStep',
        'titleStep',
        'addTemplateStep',
        'searchNameStep',
        'searchSyncStep',
        'tableStep',
        'actionsStep',
        'paginationStep'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }

}
