import { Component, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Store } from '@ngrx/store';
import { Observable, Subscription } from 'rxjs';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { debounceTime, filter, switchMap, tap, map, distinctUntilChanged } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingItem } from 'src/app/sales/store/models/shopping-item';
import { SaleState } from 'src/app/sales/store/models/sale-state.model';
import { BadgeAlign, BadgePosition } from '@progress/kendo-angular-indicators';
import { StoreERP } from 'src/app/models/store.model';

@Component({
  selector: 'app-header-shopping',
  templateUrl: './header-shopping.component.html',
  styleUrls: ['./header-shopping.component.scss'],
})
export class HeaderShoppingComponent implements OnInit, OnDestroy {
  searchProduct = new FormControl('');
  userName: string;
  storeName: string;
  shopping$: Observable<ShoppingItem[]>;
  existsProduct = false;
  loadProducts = [];
  shoppingSubscription: Subscription;
  isMenuOpen: boolean = false;
  departments: any[] = []; // Lista dinâmica para os itens do menu
  brands: any[] = []; // Propriedade para armazenar as marcas
  selectedBrandKeys: string[] = [];
  filteredProducts = [];
  store$: Observable<StoreERP[]>;

  onlyWithStock: boolean = false;
  productPromotion: boolean = false;
  percentOff: [number, number] = [0, 100];
  minPercentOff: number = 0;
  maxPercentOff: number = 100;
  smallStep: number = 5;
  largeStep: number = 20;
  markdown: boolean = false;
  oportunity: boolean = false;
  offers: boolean = false;

  @Output() filterSelected = new EventEmitter<any>();
  @Output() productsFound = new EventEmitter<any[]>();
  @Output() searchTriggered = new EventEmitter<string>();

  selectedFilter = {};

  public align: BadgeAlign = { vertical: 'top', horizontal: 'end' };
  public position: BadgePosition = 'inside';
  public themeBadge = 'warning';
  public imageLogo: string = 'assets/img/logo.png';
  public imageLogoBase64: SafeUrl;

  constructor(
    private authService: AuthService,
    private productService: ProductService,
    private store: Store<SaleState>,
    private readonly sanitizer: DomSanitizer
  ) { }

  ngOnInit(): void {
    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();

    // Configuração do logo em Base64
    const rawImageLogoBase64 = `data:img/png;base64,[encoded data, 7756 characters]`;
    this.imageLogoBase64 = this.sanitizer.bypassSecurityTrustUrl(rawImageLogoBase64);


    // Carregar dados
    this.loadDepartments();
    this.loadBrands();

    // Observável para busca de produtos
    this.searchProduct.valueChanges
      .pipe(
        debounceTime(300),
        filter((value: string) => value?.trim().length > 2),
        distinctUntilChanged(),
        switchMap((term: string) =>
          this.productService.searchProduct(this.authService.getStore(), 1, 10, term.trim())
        )
      )
      .subscribe((products) => {
        this.loadProducts = products;
        this.filterProducts();
        this.emitProducts(this.loadProducts);
      });

    // Observável do carrinho
    this.shopping$ = this.store.select((state) => state.shopping.list);
  }

  ngOnDestroy(): void {
    if (this.shoppingSubscription) {
      this.shoppingSubscription.unsubscribe();
    }
  }

  // Método para filtrar os produtos
  filterProducts(): void {
    this.filteredProducts = this.loadProducts.filter((product: any) => {
      const meetsStock = this.onlyWithStock ? product.stock > 0 : true;
      const meetsPromotion = this.productPromotion ? product.isOnPromotion : true;
      const meetsMarkdown = this.markdown ? product.isMarkdown : true;
      const meetsOportunity = this.oportunity ? product.isOportunity : true;
      const meetsOffers = this.offers ? product.isOffer : true;

      return meetsStock && meetsPromotion && meetsMarkdown && meetsOportunity && meetsOffers;
    });

    console.log('Produtos filtrados:', this.filteredProducts);
  }

  // Método chamado ao aplicar filtros
  getFilterProducts(): void {
    console.log('Aplicando filtros...');
    this.filterProducts();
  }

  selectedStore(event: any): void {
    console.log('Loja selecionada:', event);
    // Caso precise atualizar alguma variável ou aplicar filtros
    this.storeName = event?.id || ''; // Exemplo de atualização com o ID da loja selecionada
    this.filterSelected.emit({ store: event });
  }

  // Método de busca manual
  onSearch(): void {
    const searchValue = this.searchProduct.value?.trim();

    if (searchValue && searchValue.length > 2) {
      console.log('Termo de busca emitido:', searchValue);

      // Emitindo o termo de busca para o componente pai
      this.searchTriggered.emit(searchValue);

      // Realizando a busca de produtos localmente
      this.productService
        .searchProduct(this.authService.getStore(), 1, 10, searchValue)
        .subscribe((products) => {
          this.loadProducts = products;
          this.filterProducts(); // Filtra os produtos após a busca
          console.log('Produtos encontrados:', products);
        });
    } else {
      console.warn('O termo de busca deve ter pelo menos 3 caracteres.');
    }
  }

  // Carregar Marcas
  loadBrands(): void {
    // Implementação para carregar marcas, se necessário
  }

  // Quando um filtro é escolhido
  applyFilter(filter: any): void {
    console.log('Filtrando:', filter); // Log para verificar os dados do filtro
    this.selectedFilter = filter;
    this.filterSelected.emit(filter); // Emissão do evento
    console.log('Filtro emitido:', filter);
    this.closeMenu();
  }



  // Carregar os departamentos
  loadDepartments(): void {
    this.productService
      .getClasseMercadologica()
      .pipe(
        map((data) =>
          this.mapItems(
            data.filter((d) => d.tituloEcommerce != null),
            ['tituloEcommerce', 'descricaoSecao', 'descricaoCategoria'],
            ['secoes', 'categorias']
          )
        )
      )
      .subscribe((items) => (this.departments = items));
  }

  private emitProducts(products: any[]): void {
    this.productsFound.emit(products);
  }

  // Mapeamento dos dados hierárquicos
  private mapItems(items: any[], textFields: string[], childFields: string[], level: number = 0): any[] {
    const childField = childFields[level];
    const textField = textFields[level];

    return items.map((item) => {
      const result: any = {
        text: item[textField],
        path: item.url,
      };
      if (childField && item[childField]) {
        result.items = this.mapItems(item[childField], textFields, childFields, level + 1);
      }
      return result;
    });
  }

  logout(): void {
    this.authService.logout();
    console.log('Usuário deslogado.');
  }

  openMenu(): void {
    this.isMenuOpen = true;
    setTimeout(() => {
      document.querySelector('.menu-modal')?.classList.add('open');
    }, 10);
  }

  closeMenu(): void {
    const modal = document.querySelector('.menu-modal');
    modal?.classList.remove('open');
    setTimeout(() => {
      this.isMenuOpen = false;
    }, 500);
  }
}
