import {Component, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {DatePipe} from "@angular/common";
import {MatDialog} from "@angular/material/dialog";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
import {DeleteModalComponent} from "../../shared/delete_modal/delete-modal/delete-modal.component";
import { JoyrideService } from 'ngx-joyride';
import { Router } from '@angular/router';
import { ConfigService } from '@services/config.service';
import {Subnet} from "../ogdhcp/og-dhcp-subnets.component";
import {ShowImagesComponent} from "./show-images/show-images.component";
import {ManageRepositoryComponent} from "./manage-repository/manage-repository.component";

@Component({
  selector: 'app-repositories',
  templateUrl: './repositories.component.html',
  styleUrl: './repositories.component.css'
})
export class RepositoriesComponent implements OnInit {
  baseUrl: string;
  private apiUrl: string;
  dataSource = new MatTableDataSource<any>();
  length: number = 0;
  itemsPerPage: number = 10;
  page: number = 0;
  loading: boolean = false;
  filters: { [key: string]: string } = {};
  datePipe: DatePipe = new DatePipe('es-ES');
  columns = [
    {
      columnDef: 'id',
      header: 'Id',
      cell: (repository: any) => `${repository.id}`
    },
    {
      columnDef: 'name',
      header: 'Nombre de repositorio',
      cell: (repository: any) => `${repository.name}`
    },
    {
      columnDef: 'ip',
      header: 'Ip',
      cell: (repository: any) => `${repository.ip}`
    },
    {
      columnDef: 'images',
      header: 'Imágenes',
      cell: (repository: any) => `${repository.images}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (repository: any) => `${this.datePipe.transform(repository.createdAt, 'dd/MM/yyyy hh:mm:ss')}`
    }
  ];
  displayedColumns: string[] = ['id', 'name', 'ip', 'images', 'createdAt', 'actions'];

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

  ngOnInit(): void {
    this.search();
  }

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

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

  search(): void {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?page=${this.page +1 }&itemsPerPage=${this.itemsPerPage}`, { params: this.filters }).subscribe(
      data => {
        this.dataSource.data = data['hydra:member'];
        this.length = data['hydra:totalItems'];
        this.loading = false;
      },
      error => {
        console.error('Error fetching images', error);
        this.loading = false;
      }
    );
  }

  editRepository(event: MouseEvent, repository: any): void {
    event.stopPropagation();
    this.dialog.open(ManageRepositoryComponent, {
      width: '600px',
      data: repository['@id']
    }).afterClosed().subscribe(() => this.search());
  }

  deleteRepository(event: MouseEvent,command: any): void {
    event.stopPropagation();
    this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: command.name },
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.http.delete(`${this.apiUrl}/${command.uuid}`).subscribe({
          next: () => {
            this.toastService.success('Imagen eliminada con éxito');
            this.search();
          },
          error: (error) => {
            console.error('Error al eliminar la imagen:', error);
          }
        });
      }
    });
  }

  openShowImagesDialog(repository: Subnet) {
    const dialogRef = this.dialog.open(ShowImagesComponent, {
      width: '100vw',
      height: '100vh',
      maxWidth: '100vw',
      maxHeight: '100vh',
      data: { repositoryId: repository.id, repositoryName: repository.name, repositoryUuid: repository.uuid }
    });

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


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

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'titleStep',
        'addStep',
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }
}
