import {Component, Inject, Input, isDevMode, OnInit} from '@angular/core';
import {MatTableDataSource} from "@angular/material/table";
import {DatePipe} from "@angular/common";
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from "@angular/material/dialog";
import {HttpClient} from "@angular/common/http";
import {ToastrService} from "ngx-toastr";
import {JoyrideService} from "ngx-joyride";
import {ConfigService} from "@services/config.service";
import {Router} from "@angular/router";
import {Observable} from "rxjs";
import {ServerInfoDialogComponent} from "../../ogdhcp/server-info-dialog/server-info-dialog.component";
import {ImportImageComponent} from "../import-image/import-image.component";
import {ConvertImageComponent} from "../convert-image/convert-image.component";
import {DeleteModalComponent} from "../../../shared/delete_modal/delete-modal/delete-modal.component";
import {ExportImageComponent} from "../../images/export-image/export-image.component";
import {BackupImageComponent} from "../backup-image/backup-image.component";
import {ConvertImageToVirtualComponent} from "../convert-image-to-virtual/convert-image-to-virtual.component";

@Component({
  selector: 'app-show-images',
  templateUrl: './show-images.component.html',
  styleUrl: './show-images.component.css'
})
export class ShowImagesComponent 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;
  repository: any = {};
  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.image.name}`
    },
    {
      columnDef: 'remotePc',
      header: 'Remote Pc',
      cell: (image: any) => `${image.image?.remotePc}`
    },
    {
      columnDef: 'isGlobal',
      header: 'Imagen global',
      cell: (image: any) => `${image.image?.isGlobal}`
    },
    {
      columnDef: 'status',
      header: 'Estado',
      cell: (image: any) => `${image.status}`
    },
    {
      columnDef: 'imageFullsum',
      header: 'Fullsum',
      cell: (image: any) => `${image.imageFullsum}`
    },
    {
      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'];

  constructor(
    public dialog: MatDialog,
    private http: HttpClient,
    private toastService: ToastrService,
    private joyrideService: JoyrideService,
    private configService: ConfigService,
    private router: Router,
    public dialogRef: MatDialogRef<ShowImagesComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/image-image-repositories`;
  }

  ngOnInit(): void {
    console.error()
    if (this.data) {
      this.loadData();
    }
  }

  loadData(): void {
    this.loading = true;
    this.http.get<any>(`${this.apiUrl}?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}&repository.id=${this.data.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 image repositories', error);
      }
    )
  }

  getStatusLabel(status: string): string {
    switch (status) {
      case 'pending':
        return 'Pendiente';
      case 'in-progress':
        return 'En progreso';
      case 'aux-files-pending':
        return 'Archivos auxiliares pendientes';
      case 'success':
        return 'Creado con éxito';
      case 'trash':
        return 'Papelera temporal';
      case 'failed':
        return 'Fallido';
      case 'transferring':
        return 'Transfiriendo';
      default:
        return 'Estado desconocido';
    }
  }

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

  loadImageAlert(image: any): Observable<any> {
    return this.http.get<any>(`${this.apiUrl}/server/${image.uuid}/get`, {});
  }

  showImageInfo(event: MouseEvent, image:any) {
    event.stopPropagation();
    this.loading = true;
    this.loadImageAlert(image).subscribe(
      response => {
        this.alertMessage = response;

        this.dialog.open(ServerInfoDialogComponent, {
          width: '800px',
          data: {
            message: this.alertMessage
          }
        });
        this.loading = false;
      },
      error => {
        this.toastService.error(error.error['hydra:description']);
        this.loading = false;
      }
    );
  }

  importImage(): void {
    console.log(this.data)
    this.dialog.open(ImportImageComponent, {
      width: '600px',
      data: {
        repositoryUuid: this.data.repositoryUuid,
        name: this.data.repositoryName
      }
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.loadData();
      }
    });
  }

  convertImage(): void {
    this.dialog.open(ConvertImageComponent, {
      width: '600px',
      data: {
        repositoryUuid: this.data.repositoryUuid,
        name: this.data.repositoryName
      }
    }).afterClosed().subscribe((result) => {
      if (result) {
        this.loadData();
      }
    });
  }

  toggleAction(image: any, action:string): void {
    switch (action) {
      case 'get-aux':
        this.http.post(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/create-aux-files`, {}).subscribe({
          next: (message) => {
            this.toastService.success('Petición de creación de archivos auxiliares enviada');
            this.loadData()
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'delete-trash':
        if (!image.imageFullsum) {
          const dialogRef = this.dialog.open(DeleteModalComponent, {
            width: '400px',
            data: { name: image.name },
          });

          dialogRef.afterClosed().subscribe((result) => {
            this.http.delete(`${this.baseUrl}${image['@id']}`).subscribe({
              next: () => {
                this.toastService.success('Image deleted successfully');
                this.loadData()
              },
              error: (error) => {
                this.toastService.error('Error deleting image');
              }
            });
          });
        } else {
          this.http.post(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/delete-trash`,
            { repository: `/image-repositories/${this.data.repositoryUuid}` })
            .subscribe({
              next: () => {
                this.toastService.success('Petición de eliminación de la papelera temporal enviada');
                this.loadData()
              },
              error: (error) => {
                this.toastService.error(error.error['hydra:description']);
              }
            });
        }

        break;
      case 'delete-permanent':
        this.dialog.open(DeleteModalComponent, {
          width: '300px',
          data: { name: image.name },
        }).afterClosed().subscribe((result) => {
          if (result) {
            this.http.post(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/delete-permanent`, {}).subscribe({
              next: () => {
                this.toastService.success('Petición de eliminación de la papelera temporal enviada');
                this.loadData()
              },
              error: (error) => {
                this.toastService.error(error.error['hydra:description']);
              }
            });
          }
        });
        break;
      case 'recover':
        this.http.post(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/recover`, {}).subscribe({
          next: () => {
            this.toastService.success('Petición de recuperación de la imagen enviada');
            this.loadData()
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'status':
        this.http.post(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/status`, {}).subscribe({
          next: (response: any) => {
            this.toastService.info(response?.output);
            this.loadData()
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'transfer':
        this.http.get(`${this.baseUrl}${image.image['@id']}`).subscribe({
          next: (response) => {
            this.dialog.open(ExportImageComponent, {
              width: '600px',
              data: {
                image: response,
                imageImageRepository: image
              }
            });
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'transfer-global':
        this.http.post<any>(`${this.baseUrl}/image-image-repositories/server/${image.uuid}/transfer-global`, {
        }).subscribe({
          next: (response) => {
            this.toastService.success('Petición de exportación de imagen realizada correctamente');
            this.loading = false;
            this.router.navigate(['/commands-logs']);
          },
          error: error => {
            this.loading = false;
            this.toastService.error('Error en la petición de exportación de imagen');
          }
        });
        break;
      case 'backup':
        this.http.get(`${this.baseUrl}${image.image['@id']}`).subscribe({
          next: (response) => {
            this.dialog.open(BackupImageComponent, {
              width: '600px',
              data: {
                image: response,
                imageImageRepository: image
              }
            });
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      case 'convert-image-to-virtual':
        this.http.get(`${this.baseUrl}${image.image['@id']}`).subscribe({
          next: (response) => {
            this.dialog.open(ConvertImageToVirtualComponent, {
              width: '600px',
              data: {
                image: response,
                imageImageRepository: image
              }
            });
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
        break;
      default:
        console.error('Acción no soportada:', action);
        break;
    }
  }

  iniciarTour(): void {
    this.joyrideService.startTour({
      steps: [
        'imagesTitleStep',
        'addImageButton',
        'searchImagesField',
        'imagesTable',
        'actionsHeader',
        'editImageButton',
        'deleteImageButton',
        'imagesPagination'
      ],
      showPrevButton: true,
      themeColor: '#3f51b5'
    });
  }

  loadAlert(): Observable<any> {
    return this.http.post<any>(`${this.baseUrl}/image-repositories/server/${this.data.repositoryUuid}/get-collection`, {});
  }

  syncRepository() {
    this.http.post(`${this.baseUrl}/image-repositories/server/${this.data.repositoryUuid}/sync`, {})
      .subscribe(response => {
        this.toastService.success('Sincronización completada');
        this.loadData()
      }, error => {
        console.error('Error al sincronizar', error);
        this.toastService.error('Error al sincronizar');
      });
  }

  openImageInfoDialog() {
    this.loadAlert().subscribe(
      response => {
        this.alertMessage = response.output;

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

  onNoClick(): void {
    this.dialogRef.close();
  }

  protected readonly isDevMode = isDevMode;
}
