import { Component, OnInit, OnDestroy, signal, ChangeDetectionStrategy, inject } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { CartService, LanguageService } from '../../services';
import { Item } from '../../models';
import { combineLatest, Subscription } from 'rxjs';
import { LangRoutePipe } from '../../pipes/lang-route.pipe';
import { TranslatePipe } from '../../i18n/translate.pipe';
import { TranslateService } from '../../i18n/translate.service';
import { getDiscountedPrice, getMainImage, trackByItemId, getBadgeClass, getTranslatedField } from '../../utils/item.utils';
import { ProductFacade } from '../../facades/platform/product.facade';
import { CategoryFacade } from '../../facades/platform/category.facade';
import { Category } from '../../core/categories/models/category-domain.model';
import { IconComponent } from '../../shared/ui/icon/icon.component';

@Component({
  selector: 'app-subcategories',
  imports: [DecimalPipe, RouterLink, LangRoutePipe, TranslatePipe, IconComponent],
  templateUrl: './subcategories.component.html',
  styleUrls: ['./subcategories.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SubcategoriesComponent implements OnInit, OnDestroy {
  subcategories = signal<Category[]>([]);
  /** Items belonging directly to this category (when hasItems is true) */
  categoryItems = signal<Item[]>([]);
  loading = signal(true);
  error = signal<string | null>(null);

  private i18n = inject(TranslateService);
  private readonly productFacade = inject(ProductFacade);
  parentName = signal<string>('');

  private routeSubscription?: Subscription;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private categoryFacade: CategoryFacade,
    private langService: LanguageService,
    private cartService: CartService
  ) {}

  ngOnInit(): void {
    this.routeSubscription = this.route.params.subscribe(params => {
      const id = parseInt(params['id'], 10);
      this.loadForParent(id);
    });
  }

  ngOnDestroy(): void {
    this.routeSubscription?.unsubscribe();
  }

  private loadForParent(parentId: number): void {
    this.loading.set(true);
    this.categoryItems.set([]);
    this.subcategories.set([]);
    this.error.set(null);
    this.categoryFacade.selectCategory(parentId);

    combineLatest([
      this.categoryFacade.getCategoryById(parentId),
      this.categoryFacade.getChildren(parentId),
    ]).subscribe({
      next: ([parent, children]) => {
        this.parentName.set(parent ? this.categoryName(parent) : this.i18n.t('home.categoriesTitle'));
        const visibleChildren = children
          .filter(category => this.isDisplayableCategory(category))
          .sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));

        if (visibleChildren.length > 0) {
          this.subcategories.set(visibleChildren);
          this.loadCategoryItems(parentId);
        } else {
          const lang = this.langService.currentLanguage();
          this.router.navigate([`/${lang}/category`, parentId, 'items'], { replaceUrl: true });
        }

        this.loading.set(false);
      },
      error: (err) => {
        this.error.set('Failed to load subcategories');
        this.loading.set(false);
        console.error('Error loading categories:', err);
      }
    });
  }

  /** Load items that belong directly to this category */
  private loadCategoryItems(categoryId: number): void {
    this.productFacade.getProductsByCategory(categoryId, { count: 50, skip: 0 }).subscribe({
      next: (result) => {
        this.categoryItems.set(result.items);
      },
      error: () => {
        // Not critical — subcategories still work
      }
    });
  }

  private isDisplayableCategory(category: Category): boolean {
    return category.visible !== false
      && ((category.itemCount ?? 0) > 0 || category.children.length > 0);
  }

  hasSubcategories(): boolean {
    return this.subcategories().length > 0;
  }

  addToCart(itemID: number, event: Event): void {
    event.preventDefault();
    event.stopPropagation();
    this.cartService.addItem(itemID);
  }

  // TrackBy function for performance optimization
  trackByCategoryId(_index: number, category: Category): number {
    return category.id;
  }

  subcategoryChildCount(subcategory: Category): number {
    return subcategory.children.length;
  }

  subcategoryItemCount(subcategory: Category): number {
    return subcategory.itemCount ?? 0;
  }

  readonly getDiscountedPrice = getDiscountedPrice;
  readonly getMainImage = getMainImage;
  readonly trackByItemId = trackByItemId;
  readonly getBadgeClass = getBadgeClass;

  itemName(item: Item): string { return getTranslatedField(item, 'name', this.langService.currentLanguage()); }

  categoryName(cat: Category): string { return cat.translations[this.langService.currentLanguage()]?.title ?? cat.title; }
}
