import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminCategoriesFacade } from '../facade/admin-categories.facade';
import { AdminCategoryFormComponent } from '../components/admin-category-form.component';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { LanguageService } from '../../../../services/language.service';
import { DialogComponent } from '../../../../shared/ui/dialog/dialog.component';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';

@Component({
  selector: 'app-admin-category-editor-page',
  standalone: true,
  imports: [AdminCategoryFormComponent, TranslatePipe, DialogComponent, ButtonComponent],
  template: `@if (facade.draft(); as draft) {<main class="editor-page"><header><h1>{{ title() | translate }}</h1></header><app-admin-category-form [category]="draft" [parentOptions]="parentOptions()" [breadcrumb]="facade.breadcrumbFor(draft.parentId)" [children]="facade.childrenOf(draft.id)" [slugTaken]="facade.slugTaken()" [slugCheckError]="facade.slugCheckError()" [locales]="facade.supportedLocales()" [mode]="facade.editorMode()" [health]="facade.health(draft)" (categoryChange)="facade.updateDraft($event)" (saveDraft)="save(false)" (publish)="save(true)" /></main>} @else {<main class="editor-page"><p>{{ 'common.loading' | translate }}</p></main>}
  @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>
  }`,
  styles: [`.editor-page { max-width: 1120px; margin: 0 auto; padding: 24px; display: grid; gap: 16px; } .editor-page h1, .editor-page p { margin: 0; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminCategoryEditorPageComponent {
  readonly facade = inject(AdminCategoriesFacade);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);
  readonly title = computed(() => this.facade.editorMode() === 'create' ? 'adminCategories.create' : 'adminCategories.edit');

  readonly parentOptions = computed(() => {
    const draft = this.facade.draft();
    if (!draft) return [];
    const excluded = new Set<string>([draft.id, ...this.descendantIds(draft.id)]);
    return this.facade.categories().filter(category => !excluded.has(category.id) && !category.deletedAt);
  });

  constructor() {
    const id = this.route.snapshot.paramMap.get('id');
    if (this.facade.categories().length === 0) {
      this.facade.loadList();
    }
    this.facade.ensureLocalesLoaded();
    if (!id) {
      this.facade.startCreate();
    } else {
      this.facade.loadForEdit(id);
    }
  }

  save(publish: boolean): void {
    this.facade.saveDraft(publish, () => {
      void this.router.navigate([this.languageService.currentLanguage(), 'backoffice', 'categories']);
    });
  }

  private descendantIds(id: string): string[] {
    return this.facade.childrenOf(id).flatMap(child => [child.id, ...this.descendantIds(child.id)]);
  }
}
