import { ChangeDetectionStrategy, Component, computed, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { AdminOrdersFacade } from '../facade/admin-orders.facade';
import { AdminOrderStatus, TERMINAL_ORDER_STATUSES } from '../models/admin-order.model';
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 '../components/order-timeline/order-timeline.component';
import { ConfirmDialogComponent } from '../../../../shared/ui/confirm-dialog/confirm-dialog.component';
import { OrderTotalFormulaComponent } from '../components/order-total-formula/order-total-formula.component';

const WORKFLOW_STEPS: AdminOrderStatus[] = ['pending', 'processing', 'shipped', 'delivered'];

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

  readonly statuses: AdminOrderStatus[] = ['pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'];
  /** Terminal statuses are only reachable via the confirm-gated cancel()/requestRefund(), never the raw dropdown. */
  readonly selectableStatuses: AdminOrderStatus[] = this.statuses.filter(status => !TERMINAL_ORDER_STATUSES.includes(status));
  readonly workflowSteps = WORKFLOW_STEPS;
  readonly noteDraft = signal('');
  readonly pendingCancelId = signal<string | null>(null);
  readonly pendingRefundId = signal<string | null>(null);
  readonly internalNoteDraft = signal('');

  readonly isTerminal = computed(() => {
    const order = this.facade.selected();
    return !!order && TERMINAL_ORDER_STATUSES.includes(order.status);
  });

  readonly currentStepIndex = computed(() => {
    const order = this.facade.selected();
    if (!order) return -1;
    return WORKFLOW_STEPS.indexOf(order.status);
  });

  readonly timelineEntries = computed<OrderTimelineEntry[]>(() => {
    const order = this.facade.selected();
    if (!order) return [];
    return 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),
      }),
      actor: entry.actor,
    }));
  });

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

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

  viewCustomer(email: string): void {
    void this.router.navigate([this.languageService.currentLanguage(), 'backoffice', 'customers', encodeURIComponent(email)]);
  }

  setStatus(id: string, status: AdminOrderStatus): void {
    if (TERMINAL_ORDER_STATUSES.includes(status)) {
      // Unreachable from the dropdown (options are filtered), but guard anyway
      // since terminal transitions must always go through the confirm dialog.
      return;
    }
    this.facade.setStatus(id, status);
  }

  cancel(id: string): void {
    this.pendingCancelId.set(id);
  }

  confirmCancel(): void {
    const id = this.pendingCancelId();
    if (id) {
      this.facade.cancelOrder(id);
    }
    this.pendingCancelId.set(null);
  }

  requestRefund(id: string): void {
    this.pendingRefundId.set(id);
  }

  confirmRefund(): void {
    const id = this.pendingRefundId();
    if (id) {
      this.facade.requestRefund(id);
    }
    this.pendingRefundId.set(null);
  }

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

  submitInternalNote(id: string): void {
    this.facade.addNote(id, this.internalNoteDraft(), true);
    this.internalNoteDraft.set('');
  }

  printInvoice(): void {
    window.print();
  }
}
