import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import { AdminCategoriesFacade } from '../facade/admin-categories.facade';
import { AdminCategoriesListComponent } from '../components/admin-categories-list.component';
import { LanguageService } from '../../../../services/language.service';
import { TranslateService } from '../../../../i18n/translate.service';
import { ConfirmDialogComponent } from '../../../../shared/ui/confirm-dialog/confirm-dialog.component';
import { DialogComponent } from '../../../../shared/ui/dialog/dialog.component';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
import { TranslatePipe } from '../../../../i18n/translate.pipe';

@Component({
  selector: 'app-admin-categories-list-page',
  standalone: true,
  imports: [AdminCategoriesListComponent, ConfirmDialogComponent, DialogComponent, ButtonComponent, TranslatePipe],
  template: `<app-admin-categories-list
    [treeRows]="facade.visibleTreeRows()"
    [flatCategories]="facade.filteredCategories()"
    [allCategories]="facade.categories()"
    [filters]="facade.filters()"
    [loading]="facade.loading()"
    [error]="facade.error()"
    [viewMode]="facade.viewMode()"
    [density]="facade.density()"
    [visibleColumns]="facade.visibleColumns()"
    [selectedIds]="facade.selectedIds()"
    [dashboardStats]="facade.dashboardStats()"
    [health]="healthFn"
    [isExpanded]="isExpandedFn"
    [canDelete]="canDeleteFn"
    (filtersChange)="facade.updateFilters($event)"
    (create)="create()"
    (edit)="edit($event)"
    (delete)="deleteOne($event)"
    (restore)="facade.restoreOne($event)"
    (toggleVisible)="facade.setVisible($event.id, $event.visible)"
    (reorder)="facade.reorder($event.id, $event.targetId)"
    (toggleExpand)="facade.toggleExpanded($event)"
    (jumpToParent)="jumpToParent($event)"
    (expandAll)="facade.expandAll()"
    (collapseAll)="facade.collapseAll()"
    (selectionChange)="facade.toggleSelection($event.id, $event.checked)"
    (selectAll)="facade.toggleAll($event)"
    (bulkVisibility)="facade.applyBulkVisibility($event)"
    (bulkDelete)="bulkDelete()"
    (bulkDuplicate)="facade.applyBulkDuplicate()"
    (bulkAssignParent)="facade.applyBulkAssignParent($event)"
    (bulkAssignImage)="facade.applyBulkAssignImage($event)"
    (bulkExport)="facade.exportSelectedAsCsv()"
    (viewModeChange)="facade.setViewMode($event)"
    (densityChange)="facade.setDensity($event)"
    (columnToggle)="facade.setColumnVisible($event.column, $event.visible)" />
    <app-confirm-dialog
      [open]="!!pendingDeleteId()"
      [titleText]="'adminCategories.deleteTitle' | translate"
      [message]="'adminCategories.confirmDelete' | translate"
      [destructive]="true"
      (confirmed)="confirmDelete()"
      (cancelled)="pendingDeleteId.set(null)" />
    <app-confirm-dialog
      [open]="bulkDeleteConfirmOpen()"
      [titleText]="'adminCategories.deleteTitle' | translate"
      [message]="'adminCategories.confirmBulkDelete' | translate"
      [destructive]="true"
      (confirmed)="confirmBulkDelete()"
      (cancelled)="bulkDeleteConfirmOpen.set(false)" />
    @if (deleteBlockedMessage()) {
      <app-dialog [open]="true" [titleText]="'adminCategories.deleteBlocked' | translate" size="sm" (closed)="deleteBlockedMessage.set(null)">
        <p>{{ deleteBlockedMessage() }}</p>
        <div class="app-confirm-dialog__actions">
          <app-button variant="primary" (click)="deleteBlockedMessage.set(null)">{{ 'common.confirm' | translate }}</app-button>
        </div>
      </app-dialog>
    }
    @if (facade.mutationError()) {
      <app-dialog [open]="true" [titleText]="'common.errorTitle' | translate" size="sm" (closed)="facade.mutationError.set(null)">
        <p>{{ 'common.errorDescription' | translate }}</p>
        <div class="app-confirm-dialog__actions">
          <app-button variant="primary" (click)="facade.mutationError.set(null)">{{ 'common.confirm' | translate }}</app-button>
        </div>
      </app-dialog>
    }`,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminCategoriesListPageComponent {
  readonly facade = inject(AdminCategoriesFacade);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);
  private readonly translate = inject(TranslateService);

  readonly healthFn = (category: Parameters<AdminCategoriesFacade['health']>[0]) => this.facade.health(category);
  readonly isExpandedFn = (id: string) => this.facade.isExpanded(id);
  readonly canDeleteFn = (id: string) => this.facade.canDelete(id);

  readonly pendingDeleteId = signal<string | null>(null);
  readonly bulkDeleteConfirmOpen = signal(false);
  readonly deleteBlockedMessage = signal<string | null>(null);

  constructor() {
    this.facade.loadList();
    this.facade.loadDashboardStats();
  }

  create(): void { this.facade.startCreate(); void this.router.navigate([this.lang(), 'backoffice', 'categories', 'create']); }
  edit(id: string): void { this.facade.loadForEdit(id); void this.router.navigate([this.lang(), 'backoffice', 'categories', id, 'edit']); }

  jumpToParent(id: string): void {
    const category = this.facade.categories().find(c => c.id === id);
    if (category?.parentId) {
      this.facade.expandAncestorsOf(id);
      queueMicrotask(() => document.getElementById(`category-tree-row-${category.parentId}`)?.focus());
    }
  }

  deleteOne(id: string): void {
    if (!this.facade.canDelete(id)) {
      this.deleteBlockedMessage.set(this.translate.t('adminCategories.deleteBlocked'));
      return;
    }
    this.pendingDeleteId.set(id);
  }

  confirmDelete(): void {
    const id = this.pendingDeleteId();
    if (id) {
      this.facade.deleteOne(id);
    }
    this.pendingDeleteId.set(null);
  }

  bulkDelete(): void {
    this.bulkDeleteConfirmOpen.set(true);
  }

  confirmBulkDelete(): void {
    this.facade.applyBulkDelete();
    this.bulkDeleteConfirmOpen.set(false);
  }

  private lang(): string {
    return this.languageService.currentLanguage();
  }
}
