import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminProductsFacade } from '../facade/admin-products.facade';
import { AdminProductFormComponent } from '../components/admin-product-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-product-editor-page',
  standalone: true,
  imports: [AdminProductFormComponent, TranslatePipe, DialogComponent, ButtonComponent],
  template: `@if (facade.draft(); as draft) {<main class="editor-page"><header><h1>{{ title() | translate }}</h1></header><app-admin-product-form [product]="draft" [categories]="facade.categories()" [allProducts]="facade.products()" [locales]="facade.supportedLocales()" [mode]="facade.editorMode()" [health]="facade.health(draft)" (productChange)="facade.updateDraft($event)" (save)="save()" /></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 AdminProductEditorPageComponent {
  readonly facade = inject(AdminProductsFacade);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);
  readonly title = computed(() => this.facade.editorMode() === 'create' ? 'adminProducts.create' : this.facade.editorMode() === 'duplicate' ? 'adminProducts.duplicate' : 'adminProducts.edit');

  constructor() {
    this.facade.loadCategories();
    this.facade.ensureLocalesLoaded();
    const id = this.route.snapshot.paramMap.get('id');
    const mode = this.route.snapshot.routeConfig?.path?.includes('duplicate') ? 'duplicate' : this.route.snapshot.routeConfig?.path?.includes('edit') ? 'edit' : 'create';
    if (mode === 'create') {
      this.facade.startCreate();
    } else if (id) {
      this.facade.loadForEdit(id, mode);
    }
  }

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