import { Component, Input, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { MatTableDataSource } from '@angular/material/table';
import { DatePipe } from '@angular/common';
import { CreateImageComponent } from './create-image/create-image.component';
import { ConfigService } from '@services/config.service';
import { JoyrideService } from 'ngx-joyride';

@Component({
  selector: 'app-images',
  templateUrl: './images.component.html',
  styleUrls: ['./images.component.css']
})
export class ImagesComponent 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 } = {};
  alertMessage: string | null = null;
  datePipe: DatePipe = new DatePipe('es-ES');
  columns = [
    {
      columnDef: 'id',
      header: 'Id',
      cell: (image: any) => `${image.id}`
    },
    {
      columnDef: 'name',
      header: 'Nombre de imagen',
      cell: (image: any) => `${image.name}`
    },
    {
      columnDef: 'imageRepositories',
      header: 'Repositorios',
      cell: (image: any) => `${image.imageRepositories}`
    },
    {
      columnDef: 'remotePc',
      header: 'Remote Pc',
      cell: (image: any) => `${image.remotePc}`
    },
    {
      columnDef: 'isGlobal',
      header: 'Imagen Global',
      cell: (image: any) => `${image.isGlobal}`
    },
    {
      columnDef: 'createdAt',
      header: 'Fecha de creación',
      cell: (image: any) => `${this.datePipe.transform(image.createdAt, 'dd/MM/yyyy hh:mm:ss')}`
    }
  ];
  displayedColumns = [...this.columns.map(column => column.columnDef), 'actions'];

  @Input() repositoryUuid: any
  private repositoryId: any;

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

  ngOnInit(): void {
    if (this.repositoryUuid) {
      this.loadRepository()
    } else {
      this.search();
    }
  }

  loadRepository(): void {
    this.http.get<any>(`${this.baseUrl}/image-repositories/${this.repositoryUuid}`, {}).subscribe(
      data => {
        this.repositoryId = data.id;
        this.search();
      },
      error => {
        console.error('Error fetching image repositories', error);
      }
    )
  }

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

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

  search(): void {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}&repositoryId=${this.repositoryId}`, { 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;
      }
    );
  }

  editImage(event: MouseEvent, image: any): void {
    event.stopPropagation();
    this.dialog.open(CreateImageComponent, {
      width: '800px',
      data: image['@id']
    }).afterClosed().subscribe(() => 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: [
        'imagesTitleStep',
        'addImageButton',
        'searchImagesField',
        'imagesTable',
        'actionsHeader',
        'editImageButton',
        'deleteImageButton',
        'imagesPagination'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }
}
