import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { AdminOrdersFacade, AdminOrderColumn, ALL_ORDER_COLUMNS } from '../facade/admin-orders.facade';
import { AdminOrderStatus, TERMINAL_ORDER_STATUSES } from '../models/admin-order.model';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
import { LanguageService } from '../../../../services/language.service';
import { ButtonComponent } from '../../../../shared/ui/button/button.component';
import { InputComponent } from '../../../../shared/ui/input/input.component';
import { BadgeComponent } from '../../../../shared/ui/badge/badge.component';
import { TableComponent } from '../../../../shared/ui/table/table.component';
import { PaginationComponent } from '../../../../shared/ui/pagination/pagination.component';
import { EmptyStateComponent } from '../../../../shared/ui/empty-state/empty-state.component';
import { SkeletonComponent } from '../../../../shared/ui/skeleton/skeleton.component';
import { CardComponent } from '../../../../shared/ui/card/card.component';
import { OrdersDashboardComponent } from '../components/orders-dashboard/orders-dashboard.component';
import { ConfirmDialogComponent } from '../../../../shared/ui/confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-admin-orders-list-page',
  standalone: true,
  imports: [CommonModule, FormsModule, TranslatePipe, ButtonComponent, InputComponent, BadgeComponent, TableComponent, PaginationComponent, EmptyStateComponent, SkeletonComponent, CardComponent, OrdersDashboardComponent, ConfirmDialogComponent],
  templateUrl: './admin-orders-list-page.component.html',
  styleUrls: ['./admin-orders-list-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminOrdersListPageComponent {
  readonly facade = inject(AdminOrdersFacade);
  private readonly router = inject(Router);
  private readonly languageService = inject(LanguageService);

  readonly statuses = ['all', 'pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded'] as const;
  /** Bulk status change excludes terminal statuses - cancel/refund must go through the confirm-gated single-order flow. */
  readonly bulkSelectableStatuses: AdminOrderStatus[] = (['pending', 'processing', 'shipped', 'delivered'] as const)
    .filter(status => !TERMINAL_ORDER_STATUSES.includes(status));
  readonly allColumns = ALL_ORDER_COLUMNS;
  protected readonly columnsPanelOpen = signal(false);
  protected readonly bulkStatusValue = signal<AdminOrderStatus>('pending');
  protected readonly bulkDeleteConfirmOpen = signal(false);

  constructor() {
    this.facade.loadList();
    this.facade.loadDashboardStats();
  }

  totalPages(): number {
    return Math.max(1, Math.ceil(this.facade.total() / this.facade.filters().pageSize));
  }

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

  isSelected(id: string): boolean {
    return this.facade.selectedIds().includes(id);
  }

  isColumnVisible(column: AdminOrderColumn): boolean {
    return this.facade.visibleColumns().includes(column);
  }

  applyBulkStatus(): void {
    this.facade.applyBulkStatus(this.bulkStatusValue());
  }

  bulkDelete(): void {
    this.bulkDeleteConfirmOpen.set(true);
  }

  confirmBulkDelete(): void {
    this.facade.applyBulkDelete();
    this.bulkDeleteConfirmOpen.set(false);
  }

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

  exportCsv(): void {
    const csv = this.facade.exportCsv();
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'orders.csv';
    link.click();
    URL.revokeObjectURL(url);
  }
}
