import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { CreateSubnetComponent } from './create-subnet/create-subnet.component';
import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { AddClientsToSubnetComponent } from './add-clients-to-subnet/add-clients-to-subnet.component';
import { ServerInfoDialogComponent } from "./server-info-dialog/server-info-dialog.component";
import { Observable } from "rxjs";
import { JoyrideService } from 'ngx-joyride';
import { DeleteModalComponent } from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { ShowClientsComponent } from "./show-clients/show-clients.component";
import { ConfigService } from '@services/config.service';

export interface Subnet {
  '@id': string;
  '@type': string;
  name: string;
  netmask: string;
  ipAddress: string;
  nextServer: string;
  router: string;
  bootFileName: string;
  synchronized: boolean;
  serverId: number;
  clients: [];
  createdAt: string;
  createdBy: string;
  uuid: string;
  id: number;
}

@Component({
  selector: 'app-ogdhcp',
  templateUrl: './og-dhcp-subnets.component.html',
  styleUrls: ['./og-dhcp-subnets.component.css']
})
export class OgDhcpSubnetsComponent implements OnInit {
  baseUrl: string;
  displayedColumns: string[] = ['id', 'name', 'netmask', 'ipAddress', 'synchronized', 'serverId', 'clients', 'actions'];
  dataSource = new MatTableDataSource<Subnet>([]);
  length = 0;
  itemsPerPage: number = 10;
  page = 0;
  filters: { [key: string]: string } = {};
  pageSizeOptions: number[] = [5, 10, 20];
  alertMessage: string | null = null;
  loading: boolean = false;

  @ViewChild(MatPaginator) paginator: MatPaginator | undefined;

  columns = [
    { columnDef: 'id', header: 'ID', cell: (subnet: Subnet) => subnet.id },
    { columnDef: 'name', header: 'Name', cell: (subnet: Subnet) => subnet.name },
    { columnDef: 'netmask', header: 'Netmask', cell: (subnet: Subnet) => subnet.netmask },
    { columnDef: 'ipAddress', header: 'IP Address', cell: (subnet: Subnet) => subnet.ipAddress },
    { columnDef: 'synchronized', header: 'Sincronizado', cell: (subnet: Subnet) => `${subnet.synchronized}` },
    { columnDef: 'serverId', header: 'Id Servidor DHCP', cell: (subnet: Subnet) => subnet.serverId },
    { columnDef: 'clients', header: 'Lista de clientes', cell: (subnet: Subnet) => `${subnet.clients}` },
  ];

  private apiUrl: string;

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

  ngOnInit() {
    this.loading = true;
    this.loadAlert()
    this.syncSubnets()
  }

  loadSubnets() {
    this.http.get<any>(`${this.baseUrl}/subnets?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}`).subscribe({
      next: (response) => {
        this.dataSource.data = response['hydra:member'];
        this.length = response['hydra:totalItems'];
      },
      error: error => {
        this.toastService.error(error.error['hydra:description']);
      }
    });

    if (this.paginator) {
      this.dataSource.paginator = this.paginator;
    }
  }

  syncSubnets() {
    this.http.post(`${this.apiUrl}/sync`, {})
      .subscribe(response => {
        this.toastService.success('Sincronización con componente DHCP exitosa');
        this.loadSubnets()
        this.loading = false;
      }, error => {
        this.loading = false;
        this.toastService.error('Error al sincronizar');
      });
  }

  toggleAction(subnet: any, action: string): void {
    switch (action) {
      case 'get':
        this.http.post(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/get`, {}).subscribe({
          next: () => {
            this.toastService.success('Subred sincronizada con servidor');
            this.loadSubnets()
          },
          error: (error) => {
            console.error('Error al crear subred en servidor', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'post':
        this.http.post(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/post`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de instalación enviada');
            this.loadSubnets()
          },
          error: (error) => {
            console.error('Error al crear subred en servidor', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'put':
        this.http.put(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/put`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de actualizacion enviada');
            this.loadSubnets();
          },
          error: (error) => {
            console.error('Error al actualizar la subred en el servidor', error);
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'delete':
        const dialogRef = this.dialog.open(DeleteModalComponent, {
          width: '300px',
          data: { name: subnet.name }
        });

        dialogRef.afterClosed().subscribe(result => {
          if (result) {
            this.http.delete(`${this.baseUrl}/og-dhcp/server/${subnet.uuid}/delete`, {}).subscribe({
              next: () => {
                this.toastService.success('Subred eliminada exitosamente');
                this.loadSubnets();
              },
              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;
    }
  }

  addSubnet() {
    const dialogRef = this.dialog.open(CreateSubnetComponent, {
      width: '600px'
    });

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

  editSubnet(subnet: Subnet) {
    const dialogRef = this.dialog.open(CreateSubnetComponent, {
      width: '600px',
      data: subnet
    });

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

  loadAlert(): Observable<any> {
    return this.http.get<any>(`${this.baseUrl}/og-dhcp/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);
      }
    );
  }

  openShowClientsDialog(subnet: Subnet) {
    const dialogRef = this.dialog.open(ShowClientsComponent, {
      width: '100vw',
      height: '100vh',
      maxWidth: '100vw',
      maxHeight: '100vh',
      data: { subnetId: subnet.id, subnetName: subnet.name, subnetUuid: subnet.uuid }
    });

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

  addClientsToSubnet(subnet: Subnet) {
    const dialogRef = this.dialog.open(AddClientsToSubnetComponent, {
      width: '800px',
      data: { subnetUuid: subnet.uuid, subnetName: subnet.name }
    });

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

  onPageChange(event: any) {
    this.page = event.pageIndex;
    this.itemsPerPage = event.pageSize;
    this.loadSubnets();
  }

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

}
