import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { EquipmentsListItem, PendingEquipmentsListItem } from '../../../interfaces/equipment-management.interface';
import { MatDialog } from '@angular/material/dialog';
import { ResourcesService } from '../../../services/resources.service';
import { EquipmentManagementService } from '../../../services/equipment-management.service';
import { PreCodeDetailsComponent } from './pre-code-details/pre-code-details.component';
import { ChangePreCodeStatusComponent } from './change-pre-code-status/change-pre-code-status.component';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-equipment-card',
    templateUrl: './equipment-card.component.html',
    styleUrl: './equipment-card.component.css',
    standalone: false
})
export class EquipmentCardComponent implements OnInit {
  @Input() pendingEquipment: PendingEquipmentsListItem | null;
  @Input() equipment: EquipmentsListItem | null;
  @Input() equipmentType: string;
  @Input() equipmentDetailsEnabled: boolean;
  @Output() refreshPendingList = new EventEmitter<string>();
  @Output() openChildren = new EventEmitter<string>();

  images: string[];
  imageIndex: number;
  equipmentLabel: string;

  constructor(
    private _dialog: MatDialog,
    private _resourcesService: ResourcesService,
    private _equipmentManagementService: EquipmentManagementService,
  ) {
    this.pendingEquipment = null;
    this.equipment = null;
    this.equipmentType = "";
    this.equipmentDetailsEnabled = true;
    this.images = [];
    this.imageIndex = 0;
    this.equipmentLabel = "";
  }

  ngOnInit(): void {
    if(this.equipmentType == 'pending'){
      this.images = this.pendingEquipment?.GALERIA_IMAGENES as string[];
      this.equipmentLabel = `${this.pendingEquipment?.TIPO_EQUIPAMIENTO} - ${this.pendingEquipment?.MODELO_EQUIPAMIENTO}`;
    }else{
      this.images = this.equipment?.GALERIA_IMAGENES as string[];
      this.equipmentLabel = `${this.equipment?.TIPO} - ${this.equipment?.MODELO}`;
    }
  }

  backward(){
    let index = this.imageIndex - 1;
    if(index < 0){
      this.imageIndex = this.images.length - 1;
    }else{
      this.imageIndex = index;
    }
  }

  forward(){
    let index = this.imageIndex + 1;
    if(index > this.images.length - 1){
      this.imageIndex = 0
    }else{
      this.imageIndex = index;
    }
  }

  action(type: string){
    if(type == 'details'){
      if(this.equipmentType == 'pending'){
        this._dialog.open(PreCodeDetailsComponent, {
          width: '480px',
          maxWidth: '480px',
          data: {
            idReg: this.pendingEquipment?.IDREG,
            preCode: this.pendingEquipment?.CODIGO,
          }
        });
      }else{
        this.openChildren.emit(this.equipment?.CODIGO);
      }
    }else if(type == 'accept'){
      this.openStatusDialog(type);
    }else if(type == 'decline'){
      this.openStatusDialog(type);
    }
  }

  openStatusDialog(action: string){
    let dialogRef = this._dialog.open(ChangePreCodeStatusComponent, {
      width: '520px',
      maxWidth: '520px',
      disableClose: true,
      data: {
        preCode: this.pendingEquipment?.CODIGO,
        status: action
      }
    });

    dialogRef.afterClosed().subscribe(res => {
      if(res != null && res != undefined && res != ''){
        this.changePendingEquipmentStatus(action, res);
      }
    })
  }

  async changePendingEquipmentStatus(newStatus: string, comments: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let formData = new FormData();
      let status = newStatus == 'decline' ? 'Rechazado' : 'Aprobado';

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('id_reg', this.pendingEquipment?.IDREG!);
      formData.append('status', status);
      formData.append('comments', comments);
      
      await lastValueFrom(this._equipmentManagementService.equipmentPreCodificationStatusUpdate(formData));
      this._resourcesService.openSnackBar('El estado del equipamiento se actualizó correctamente.');
      this.refreshPendingList.emit('refresh');
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (1).');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado (2).');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
