import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminModerationFacade } from '../facade/admin-moderation.facade';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { TranslateService } from '../../../../i18n/translate.service';
import { LanguageService } from '../../../../services/language.service';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
import { OrderTimelineComponent, OrderTimelineEntry } from '../../orders/components/order-timeline/order-timeline.component';

@Component({
  selector: 'app-admin-review-detail-page',
  standalone: true,
  imports: [CommonModule, FormsModule, TranslatePipe, ButtonComponent, BadgeComponent, OrderTimelineComponent],
  templateUrl: './admin-review-detail-page.component.html',
  styleUrls: ['./admin-review-detail-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminReviewDetailPageComponent {
  readonly facade = inject(AdminModerationFacade);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);
  private readonly translate = inject(TranslateService);

  readonly noteDraft = signal('');

  constructor() {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
      this.facade.loadDetail(id);
    }
  }

  timelineEntries(): OrderTimelineEntry[] {
    const review = this.facade.selected();
    if (!review) return [];
    return review.timeline.map(entry => {
      const status = entry.status ? this.translate.t('adminModeration.status.' + entry.status) : '';
      const eventText = this.translate.t('adminModeration.timelineEvent.' + entry.eventKey, { status });
      const actor = this.translate.t('adminModeration.actor.' + entry.actor);
      const note = entry.note ? `${eventText} — ${entry.note}` : eventText;
      return { timestamp: entry.timestamp, note: `${note} (${actor})` };
    });
  }

  back(): void {
    void this.router.navigate([this.languageService.currentLanguage(), 'backoffice', 'moderation']);
  }

  submitNote(id: string): void {
    this.facade.addNote(id, this.noteDraft());
    this.noteDraft.set('');
  }
}
