import { Component, OnDestroy, OnInit } from '@angular/core';
import { MatMenuTrigger } from '@angular/material/menu';
import { Router } from '@angular/router';
import { ImagesService } from '../../services/images.service';
import { ProductInterface } from '../../pages/linea/linea.component';
import { FormControl } from '@angular/forms';
import { debounceTime, distinctUntilChanged, of, switchMap } from 'rxjs';

@Component({
    selector: 'app-navbar',
    templateUrl: './navbar.component.html',
    styleUrl: './navbar.component.css',
    standalone: false
})
export class NavbarComponent implements OnInit, OnDestroy {
  productos: ProductInterface[] = [];
  searchControl = new FormControl('');
  public isMenuOpen = false;
  openSubMenu: string | null = null;
  public showDropdown = false;
  public showProducts = false;
  public isHoveringOnDropdown = false;
  public navOptions: any;
  currentDropdown: { [key: string]: boolean } = {};
  menu1Opciones: any[] = [
    { name: 'PF', link: '/home' },
    { name: 'AB', link: '/about' },
    { name: 'OV', link: '/contact' },
  ];

  public menu4Opciones: any;
  public resizeSubscription: any;
  public timedOutCloser: any;
  public openSection: boolean = false;
  public cleared: boolean = true;
  public isEmpty: boolean = false;

  constructor(
    private _router: Router,
    private _imageService: ImagesService
  ) {

    this._imageService.getCategory().subscribe((datos:any) => {
      this.menu4Opciones = datos;
    });

    this.searchControl.valueChanges.pipe(
      debounceTime(600),
      distinctUntilChanged(),
      switchMap(value => {
        if (!value) {
          this.productos = [];
          this.openSection = false;
          return of([]);
        }
        return this._imageService.finder(value);
      })
    ).subscribe((products: any) => {
      if (products.length > 0) {
        this.productos = products.map((product: any) => {
          if (product.URLIMG && product.URLIMG.startsWith("css/")) {
            product.img = product.URLIMG.replace("css/", "");
          } else {
            product.img = product.URLIMG || 'assets/img/ATC.png';
          }
          return product;
        });
        this.openSection = true;
        this.isEmpty = false
      } else {
        this.openSection = true;
        this.productos = [];
        this.isEmpty = true;
      }
    });
    // Cierra el menú cuando se navega a una nueva ruta
    this._router.events.subscribe(() => {
      this.openSection = false;
      // this.searchControl.reset();
    });
  }

  toggleOpenS() {
    setTimeout(() => {
      this.openSection = false;
    }, 100);
  }

  ngOnInit(): void {
    this.resizeSubscription = window.addEventListener('resize', () => {
      if (window.innerWidth >= 768) {
        this.isMenuOpen = false;
      }
    });

    this._imageService.getOptions().subscribe((response: any) => {
      // console.log(response);
      this.navOptions = response.categorias;
    })
  }

  clearInput() {
    this.searchControl.setValue('');
    this.openSection = false;
  }

  showDropdowns(menu: string, isOpen: boolean) {
    this.currentDropdown[menu] = isOpen;
  }


  toggleMenu() {
    this.isMenuOpen = !this.isMenuOpen;
  }

  toggleSubMenu(menu: string): void {
    this.openSubMenu = this.openSubMenu === menu ? null : menu;
  }

  closeMenu() {
    this.isMenuOpen = false;
    this.openSubMenu = null;
  }

  redirectHome() {
    this._router.navigate(['']);
  }

  redirectPage() {
    this._router.navigate(['404']);
  }

  openCategorySubMenu: string | null = null;

  toggleCategorySubMenu(categoria: string): void {
    // console.log(this.openCategorySubMenu)
    if (this.openCategorySubMenu === categoria) {
      this.openCategorySubMenu = null;
    } else {
      this.openCategorySubMenu = categoria;
    }
  }

  ngOnDestroy() {
    window.removeEventListener('resize', this.resizeSubscription);
  }
}
