import { ChangeDetectionStrategy, Component, computed, effect, input, output, signal } from '@angular/core';

import { Category } from '../../../../services/tenant.interface';

@Component({
  selector: 'app-category-dropdown',
  standalone: true,
  templateUrl: './category-dropdown.component.html',
  styleUrl: './category-dropdown.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CategoryDropdownComponent {
  readonly categories = input<readonly Category[]>([]);
  readonly open = input(false);
  readonly categorySelect = output<Category>();

  protected readonly activeCategory = signal<Category | null>(null);
  protected readonly subcategories = computed(() => this.activeCategory()?.subcategories ?? []);

  constructor() {
    effect(() => {
      const categories = this.categories();
      const activeCategory = this.activeCategory();

      if (!this.open()) {
        this.activeCategory.set(null);
        return;
      }

      if (activeCategory && !categories.some((category) => category.id === activeCategory.id)) {
        this.activeCategory.set(null);
      }
    });
  }

  protected selectCategory(category: Category): void {
    if (category.subcategories.length) {
      this.activeCategory.update((activeCategory) =>
        activeCategory?.id === category.id ? null : category,
      );
      return;
    }

    this.categorySelect.emit(category);
  }
}
