import {
  Component,
  computed,
  ElementRef,
  HostListener,
  inject,
  input,
  output,
  signal,
} from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { AuthUser } from '../../../services/auth/auth.interfaces';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';
import { Menu } from '../../../services/tenant.interface';
import { ButtonComponent } from '../../../../shared/components/button/button.component';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { Category } from '../../../services/tenant.interface';
import { CategoryDropdownComponent } from './category-dropdown/category-dropdown.component';

@Component({
  selector: 'app-store-header',
  imports: [
    ButtonComponent,
    CartIconComponent,
    IconButtonComponent,
    RouterLink,
    ReactiveFormsModule,
    UserDropdownComponent,
    CategoryDropdownComponent,
  ],
  templateUrl: './store-header.component.html',
  styleUrl: './store-header.component.scss',
})
export class StoreHeaderComponent {
  private readonly elementRef = inject(ElementRef<HTMLElement>);
  private readonly router = inject(Router);

  readonly logoUrl = input<string | null>(null);
  readonly backgroundImageUrl = input<string | null>(null);
  readonly cartQuantity = input<number>(0);
  readonly user = input<AuthUser | null>(null);
  readonly isAuthenticated = input<boolean>(false);
  readonly accountNavigationMenus = input<readonly Menu[]>([]);
  readonly ticketsMenu = input<Menu | null>(null);
  readonly categories = input<readonly Category[]>([]);
  readonly displayCategories = input(true);
  readonly displaySeachBar = input(true);
  readonly displayCart = input(true);
  readonly cartDisabled = input(false);
  readonly checkoutRemainingSeconds = input<number | null>(null);
  readonly cartClick = output<void>();
  readonly ticketsClick = output<void>();
  readonly loginClick = output<void>();
  readonly logoutClick = output<void>();
  readonly searchSubmit = output<string>();
  readonly categorySelect = output<Category>();

  protected readonly isUserDropdownOpen = signal(false);
  protected readonly isCategoryDropdownOpen = signal(false);
  protected readonly isMobileMenuOpen = signal(false);
  protected readonly minSearchLength = 3;
  protected readonly showSearchError = signal(false);
  protected readonly searchControl = new FormControl('', { nonNullable: true });
  protected readonly checkoutRemainingTime = computed(() => {
    const remainingSeconds = this.checkoutRemainingSeconds();

    if (remainingSeconds === null) {
      return null;
    }

    const minutes = Math.floor(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;

    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  });

  protected onCartClick(): void {
    if (this.cartDisabled()) {
      return;
    }

    this.cartClick.emit();
  }

  @HostListener('document:click', ['$event'])
  protected onDocumentClick(event: MouseEvent): void {
    if (!this.isUserDropdownOpen() && !this.isCategoryDropdownOpen() && !this.isMobileMenuOpen()) {
      return;
    }

    const target = event.target;
    if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
      this.isUserDropdownOpen.set(false);
      this.isCategoryDropdownOpen.set(false);
      this.isMobileMenuOpen.set(false);
    }
  }

  @HostListener('document:keydown.escape')
  protected onEscapeKey(): void {
    this.isUserDropdownOpen.set(false);
    this.isCategoryDropdownOpen.set(false);
    this.isMobileMenuOpen.set(false);
  }

  protected toggleUserDropdown(): void {
    if (!this.isAuthenticated()) {
      this.loginClick.emit();
      return;
    }

    this.isUserDropdownOpen.update((isOpen) => !isOpen);
  }

  protected onLoginClick(): void {
    this.isUserDropdownOpen.set(false);
    this.loginClick.emit();
  }

  protected onLogoutClick(): void {
    this.isUserDropdownOpen.set(false);
    this.logoutClick.emit();
  }

  protected submitSearch(event?: Event): void {
    event?.preventDefault();

    const term = this.searchControl.value.trim();

    if (term.length < this.minSearchLength) {
      this.showSearchError.set(true);
      return;
    }

    this.showSearchError.set(false);
    this.searchSubmit.emit(term);
  }

  protected clearSearchError(): void {
    this.showSearchError.set(false);
  }

  protected toggleCategoryDropdown(): void {
    this.isCategoryDropdownOpen.update((isOpen) => !isOpen);
  }

  protected onCategorySelect(category: Category): void {
    this.isCategoryDropdownOpen.set(false);
    this.isMobileMenuOpen.set(false);
    this.categorySelect.emit(category);
  }

  protected toggleMobileMenu(): void {
    this.isMobileMenuOpen.update((isOpen) => !isOpen);
  }

  protected onMobileAccountClick(): void {
    this.isMobileMenuOpen.set(false);
    if (!this.isAuthenticated()) {
      this.loginClick.emit();
    } else {
      const menus = this.accountNavigationMenus();
      if (menus.length > 0) {
        this.router.navigate([menus[0].route]);
      } else {
        this.router.navigate(['/cuenta']);
      }
    }
  }
}
