import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminCustomersFacade } from '../facade/admin-customers.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-customer-detail-page',
  standalone: true,
  imports: [CommonModule, TranslatePipe, ButtonComponent, BadgeComponent, OrderTimelineComponent],
  templateUrl: './admin-customer-detail-page.component.html',
  styleUrls: ['./admin-customer-detail-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminCustomerDetailPageComponent {
  readonly facade = inject(AdminCustomersFacade);
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);
  private readonly translate = inject(TranslateService);

  readonly activity = computed<OrderTimelineEntry[]>(() => {
    const customer = this.facade.selected();
    if (!customer) return [];
    return customer.orders
      .flatMap(order => order.timeline.map(entry => ({
        status: entry.status,
        timestamp: entry.timestamp,
        note: this.translate.t('adminOrders.timelineEvent.' + entry.eventKey, {
          status: this.translate.t('adminOrders.status.' + entry.status),
        }),
        orderNumber: order.orderNumber,
      })))
      .sort((a, b) => b.timestamp.localeCompare(a.timestamp));
  });

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

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

  viewOrder(id: string): void {
    void this.router.navigate([this.languageService.currentLanguage(), 'backoffice', 'orders', id]);
  }
}
