import { Component, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core';
import { FormControl } from '@angular/forms';
import { Store } from '@ngrx/store';
import { Observable, Subscription, of } 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 { ShoppingService } from 'src/app/services/shopping.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';

@Component({
  selector: 'app-header-system',
  templateUrl: './header-system.component.html',
  styleUrls: ['./header-system.component.scss'],
})
export class HeaderSystemComponent implements OnInit, OnDestroy {
  userName: string;
  storeName: string;
  shopping$: Observable<ShoppingItem[]> = of([]);
  totalItems: number = 0;
  searchControl = new FormControl('');
  shoppingSubscription: Subscription;
  isMenuOpen: boolean = false;
  public imageLogo: string = 'assets/img/logo.png';
  public imageLogoBase64: SafeUrl;

  @Output() logoutTriggered = new EventEmitter<void>();

  public align: BadgeAlign = { vertical: 'top', horizontal: 'end' };
  public position: BadgePosition = 'inside';
  public themeBadge = 'warning';

  constructor(
    private authService: AuthService,
    private shoppingService: ShoppingService,
    private sanitizer: DomSanitizer,
    private store: Store<SaleState>
  ) {}

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

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

    // Observável para itens do carrinho
    this.loadShoppingCart();

    // Configuração para busca
    this.setupSearch();
  }

  private loadShoppingCart(): void {
    // Obter a loja atual do usuário autenticado
    const store = this.authService.getStore();
  
    // Selecionar o estado do carrinho da store global (NGRX Store)
    this.shopping$ = this.store.select((state: SaleState) => state.shopping.list);
  
    // Assinar a observação do carrinho para calcular o total de itens
    this.shoppingSubscription = this.shopping$.subscribe((items: ShoppingItem[]) => {
      if (items && items.length > 0) {
        // Calcular o total de itens no carrinho
        this.totalItems = items.reduce((sum, item) => sum + (item.quantity || 0), 0);
        console.log('Itens no carrinho:', items);
        console.log('Total de itens no carrinho:', this.totalItems);
      } else {
        this.totalItems = 0;
        console.log('Carrinho vazio.');
      }
    });
  }

  private setupSearch(): void {
    this.searchControl.valueChanges
      .pipe(
        debounceTime(300),
        filter((value: string) => value?.trim().length > 2),
        distinctUntilChanged(),
        tap((term) => console.log(`Buscando por: ${term}`))
      )
      .subscribe();
  }

  openMenu(): void {
    this.isMenuOpen = true;
  }

  closeMenu(): void {
    this.isMenuOpen = false;
  }

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

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