import { ChangeDetectionStrategy, Component, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AdminTransactionsFacade } from '../facade/admin-transactions.facade';
import { AdminTransaction } from '../models/admin-transaction.model';
import { TranslatePipe } from '../../../../i18n/translate.pipe';
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 { DialogComponent } from '../../../../shared/ui/dialog/dialog.component';
import { SkeletonComponent } from '../../../../shared/ui/skeleton/skeleton.component';

@Component({
  selector: 'app-admin-transactions-list-page',
  standalone: true,
  imports: [CommonModule, FormsModule, TranslatePipe, ButtonComponent, InputComponent, BadgeComponent, TableComponent, PaginationComponent, EmptyStateComponent, DialogComponent, SkeletonComponent],
  templateUrl: './admin-transactions-list-page.component.html',
  styleUrls: ['./admin-transactions-list-page.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AdminTransactionsListPageComponent {
  readonly facade = inject(AdminTransactionsFacade);

  readonly statuses = ['all', 'pending', 'success', 'failed', 'retried'] as const;
  readonly types = ['all', 'payment', 'refund', 'qr_payment'] as const;
  readonly auditTarget = signal<AdminTransaction | null>(null);

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

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

  viewAudit(tx: AdminTransaction): void {
    this.auditTarget.set(tx);
  }

  closeAudit(): void {
    this.auditTarget.set(null);
  }

  print(): 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 = 'transactions.csv';
    link.click();
    URL.revokeObjectURL(url);
  }
}
