import { Component, OnInit, signal } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { CreatePXEImageComponent } from './create-image/create-image/create-image.component';
import { InfoImageComponent } from './info-image/info-image/info-image.component';
import { MatTableDataSource } from "@angular/material/table";
import { PageEvent } from "@angular/material/paginator";
import { ToastrService } from "ngx-toastr";
import { DatePipe } from "@angular/common";
import { DeleteModalComponent } from '../../../shared/delete_modal/delete-modal/delete-modal.component';
import { DataService } from "./data.service";
import { Observable } from "rxjs";
import { JoyrideService } from 'ngx-joyride';
import { ServerInfoDialogComponent } from "../../ogdhcp/server-info-dialog/server-info-dialog.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-pxe-images',
  templateUrl: './pxe-images.component.html',
  styleUrls: ['./pxe-images.component.css']
})
export class PXEimagesComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  images: { downloadUrl: string; name: string; uuid: string }[] = [];
  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;
  readonly panelOpenState = signal(false);
  datePipe: DatePipe = new DatePipe('es-ES');
  columns = [
    {
      columnDef: 'id',
      header: 'ID',
      cell: (user: any) => `${user.id}`
    },
    {
      columnDef: 'name',
      header: 'Og Live',
      cell: (user: any) => `${user.name}`
    },
    {
      columnDef: 'isDefault',
      header: 'Imagen por defecto',
      cell: (user: any) => `${user.isDefault}`
    },
    {
      columnDef: 'status',
      header: 'Estado',
      cell: (image: any) => `${image.status}`
    },
    {
      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 dataService: DataService,
    private configService: ConfigService,
    private toastService: ToastrService,
    private joyrideService: JoyrideService
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/og-lives`;
  }

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

  addImage(): void {
    const dialogRef = this.dialog.open(CreatePXEImageComponent, {
      width: '600px'
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.search();
    });
  }

  search(): void {
    this.dataService.getImages(this.filters).subscribe(
      data => {
        this.dataSource.data = data;
      },
      error => {
        console.error('Error fetching og lives', error);
      }
    );
  }

  getStatusLabel(status: string): { label: string; class: string } {
    const statusMap: { [key: string]: { label: string; class: string } } = {
      active: { label: 'Instalada', class: 'status-active' },
      inactive: { label: 'Sin instalar', class: 'status-inactive' },
      pending: { label: 'Instalando...', class: 'status-installing' },
      failed: { label: 'Fallido', class: 'status-failed' }
    };

    return statusMap[status] || { label: 'Desconocido', class: 'status-default' };
  }


  toggleAction(image: any, action: string): void {
    switch (action) {
      case 'set-default':
        this.http.post(`${this.apiUrl}/server/${image.uuid}/set-default`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de cambio de imagen enviada');
            this.search();
          },
          error: (error) => {
            console.error(error.error['hydra:description']);
            this.toastService.error('Error:' + error.error['hydra:description']);
          }
        });
        break;
      case 'install':
        this.http.post(`${this.apiUrl}/server/${image.uuid}/install`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de instalación enviada');
            this.search();
          },
          error: (error) => {
            console.error(error.error['hydra:description']);
            this.toastService.error('Error:' + error.error['hydra:description']);
          }
        });
        break;
      case 'uninstall':
        this.http.post(`${this.apiUrl}/server/${image.uuid}/uninstall`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de desinstalación enviada');
            this.search();
          },
          error: (error) => {
            console.error(error.error['hydra:description']);
            this.toastService.error('Error:' + error.error['hydra:description']);
          }
        });
        break;
      default:
        console.error('Acción no soportada:', action);
        break;
    }
  }

  editImage(image: any): void {
    const dialogRef = this.dialog.open(CreatePXEImageComponent, {
      width: '700px',
      data: image
    });

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

  deleteImage(image: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '400px',
      data: { name: image.name }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        const apiUrl = `${this.baseUrl}${image['@id']}`;

        this.http.delete(apiUrl).subscribe({
          next: () => {
            this.search();
            this.toastService.success('oG Live deleted successfully');
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
      } else {
        console.log('ogLive deletion cancelled');
      }
    });
  }

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

  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);
      }
    });
  }

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

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

  openSubnetInfoDialog() {
    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);
      }
    );
  }

  syncOgBoot(): void {
    this.http.post(`${this.apiUrl}/sync`, {})
      .subscribe(response => {
        this.toastService.success('Sincronización con oGBoot exitosa');
        this.search()
      }, error => {
        console.error('Error al sincronizar', error);
        this.toastService.error('Error al sincronizar');
      });
  }

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

}
