import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProductsService } from '../../services/products.service';
import { ImagesService } from '../../services/images.service';
import { lastValueFrom } from 'rxjs';

export interface ProductInterface {
  ALCANCE: string | null;
  AMCA: string | null;
  CERTIFICADO: string | null;
  COMPRAWEB: string | null;
  DESCRIPCION: string | null;
  DETALLE1: string | null;
  DETALLE2: string | null;
  EASYVENTURL: string | null;
  FORMATO: string | null;
  FREG: string | null;
  FUPD: string | null;
  HMX: string | null;
  ID: string | null;
  LINEA: string | null;
  MODELO: string | null;
  MONEDA: string | null;
  NOTAS: string | null;
  ORDEN: number | null;
  SALTO: null;
  SUBMODELO: null;
  img: null;
}
@Component({
  selector: 'app-linea',
  templateUrl: './linea.component.html',
  styleUrls: ['./linea.component.css'],
  standalone: false
})
export class LineaComponent implements OnInit {
  public typeLine: string = '';
  public typeBann: string = 'assets/img/bg-hab.jpg';
  public products: ProductInterface[] = [];
  public option: string | null = "";
  public isLoading = true;
  public aplicationOptions: any[] = [];
  public linea: any = "";
  public producto: any = "";
  private basicurlimg = 'ALP/';
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private _productService: ProductsService,
    private imageService: ImagesService
  ) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      let urlTest = this.router.url.split('/');

      const tipo: any = params.get('tipo');
      this.producto = params.get('tipo');

      if (urlTest[1] == 'aplicacion') {
        this.linea = params.get('tipo');
        this.porAplicacion();
        this.cargarDatos(tipo);
      } else if (tipo) {
        this.isLoading = true;
        this.products = [];
        this.option = this.capitalizeFirstLetter(tipo);
        this.cargarDatos(tipo);
        this.getProducts();
      }
    });
  }

  capitalizeFirstLetter(val: string | null): string {
    if (!val) return '';
    return val.charAt(0).toUpperCase() + val.slice(1);
  }

  getProducts(): void {
    if (!this.option) return;

    this.imageService.getProducts(this.option).subscribe((response: any) => {
      // console.log(response);
      let productsAux: ProductInterface[] = [];
      for (const product of response) {
        let descClean = product.DESCRIPCION
          ? product.DESCRIPCION.replace(/<\/?[^>]+(>|$)/g, "")
          : '';
        product.DESCRIPCION = descClean;
        if (product.URLIMG && product.URLIMG.startsWith("css/")) {
          product.img = product.URLIMG.replace("css/", "");
        } else {
          product.img = product.URLIMG || 'assets/img/ATC.png';
        }
        productsAux.push(product);
      }
      this.products = productsAux;
      // console.log(this.products);
      this.isLoading = false;
    });
  }

  cargarDatos(tipo: any): void {
    switch (tipo) {
      case 'hábitat':
        this.typeLine = 'Línea Hábitat';
        this.typeBann = 'assets/img/bg-hab.jpg';
        break;
      case 'comercial':
        this.typeLine = 'Línea Comercial';
        this.typeBann = 'assets/img/bg-com.jpg';
        break;
      case 'industrial':
        this.typeLine = 'Línea Industrial';
        this.typeBann = 'assets/img/bg-ind.jpg';
        break;
      case 'aplicacion':
        this.typeLine = 'Por Aplicación';
        this.isLoading = false;
        this.imageService.getCategory().subscribe((response: any) => {
          for (let index = 0; index < response.length; index++) {
            this.aplicationOptions.push({ name: response[index].NOMBRE, link: response[index].ID, URLB: this.basicurlimg + response[index].URLB, img: this.basicurlimg + response[index].URLB });
          }
        });
        break;
      default:
        this.imageService.getInfoBanner(tipo).subscribe((response: any) => {
          if (response.length > 0) {
            this.typeLine = response[0]['NOMBRE'];
            this.typeBann = this.basicurlimg + response[0]['URLB'];
            console.log(this.typeBann);
          } else {
            this.typeLine = 'Categoría Desconocida';
            this.typeBann = 'assets/img/bg-com.jpg';
          }
        });
        break;
    }
  }
  porAplicacion() {
    let strProduct = this.producto
    this._productService.getProductCategory(strProduct).subscribe((response: any) => {
      let productsAux: ProductInterface[] = [];

      for (const product of response) {
        let descClean = product.DESCRIPCION
          ? product.DESCRIPCION.replace(/<\/?[^>]+(>|$)/g, "")
          : '';

        product.DESCRIPCION = descClean;

        if (product.URLIMG && product.URLIMG.startsWith("css/")) {
          product.img = product.URLIMG.replace("css/", "");
        } else {
          product.img = product.URLIMG || 'assets/img/ATC.png';
        }

        productsAux.push(product);
      }

      this.products = productsAux;
      // console.log(strProduct);
      this.isLoading = false;

    });
  }
}
