import { Component } from '@angular/core';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { ImagesService } from '../../services/images.service';
import { lastValueFrom } from 'rxjs';
import { ProductInterface } from '../linea/linea.component';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-producto',
    templateUrl: './producto.component.html',
    styleUrl: './producto.component.css',
    standalone: false
})
export class ProductoComponent {
  public isLoading: boolean;
  public hasError: boolean;
  public errorStr: string;
  public product: ProductInterface | null;
  public option: string | null = "";
  public typeLine: any;
  public typeBann: any;
  public href: string = '';
  private basicurlimg = 'https://www.atcfans.com/ALP/';
  constructor(
    private route: ActivatedRoute,
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
    private imageService: ImagesService,
    private http: HttpClient
  ) {
    this.functAddSVGIcon();
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.product = null;
  }

  ngOnInit() {
    this.route.paramMap.subscribe(params => {
      this.resetState();
      this.option = params.get('producto');
      this.typeBann = params.get('tipo');
      this.cargarDatos(params.get('tipo'));
      this.getProductInfo();
    });
  }

  resetState() {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.product = null;
  }

  fileExists(fileUrl: string): Promise<boolean> {
    return fetch(fileUrl, { method: 'HEAD' })
      .then(response => response.ok)
      .catch(() => false);
  }

  async getProductInfo() {
    try {
      let product: any = await lastValueFrom(this.imageService.findOne(this.option!));
      if (Object.keys(product).length <= 0) {
        this.hasError = true;
        this.errorStr = 'El producto solicitado no se encuentra dentro de los registros del sistema.';
      } else {
        let descClean = product.DESCRIPCION
          ? product.DESCRIPCION.replace(/<\/?[^>]+(>|$)/g, "")
          : '';
        product.DESCRIPCION = descClean;
        // Verificar si la ruta de la imagen comienza con "css/" y ajustarla
        if (product.URLIMG && product.URLIMG.startsWith("css/")) {
          product.img = product.URLIMG.replace("css/", "");
        } else {
          product.img = product.URLIMG || 'assets/img/ATC.png'; // Imagen por defecto
        }
        this.product = product as ProductInterface;
        this.imageService.productFile(this.product.SUBMODELO || "").subscribe((data: any) => {
          this.href = `../${data.ARCH_FICH}`;
        });
      }
      this.isLoading = false;
    } catch (error: any) {
      // console.log(error);
    }
  }

  functAddSVGIcon() {
    this._matIconRegistry.addSvgIcon(
      'catalogo',
      this._domSanitizer.bypassSecurityTrustResourceUrl('assets/img/1atc.svg')
    );
    this._matIconRegistry.addSvgIcon(
      'info',
      this._domSanitizer.bypassSecurityTrustResourceUrl('assets/img/2atc.svg')
    );
  }

  cargarDatos(tipo: any) {
    if (tipo === 'hábitat') {
      this.typeLine = 'Línea Hábitat';
      this.typeBann = 'assets/img/bg-hab.jpg';
    } else if (tipo === 'comercial') {
      this.typeLine = 'Línea Comercial';
      this.typeBann = 'assets/img/bg-com.jpg';
    } else if (tipo === 'industrial') {
      this.typeLine = 'Línea Industrial';
      this.typeBann = 'assets/img/bg-ind.jpg';
    } else if (tipo === 'aplicacion') {
      this.typeLine = 'Por Aplicación';
      this.typeBann = 'assets/img/bg-hab.jpg';
    } else {
      this.imageService.getInfoBanner(tipo).subscribe((response: any) => {
        this.typeLine = response[0]['NOMBRE'];
        this.typeBann = this.basicurlimg+response[0]['URLB'];
      });
    }
  }
}
