import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  inject,
  Input,
  Output,
} from '@angular/core';
import { TransactionService } from '@service/transaction.service';
import { Observable } from 'rxjs';
import { AsyncPipe, CurrencyPipe, DatePipe, NgIf } from '@angular/common';
import { TransactionData } from '../../model/TransactionData';

const PER_PAGE = 5;

@Component({
  standalone: true,
  selector: 'app-transaction-history',
  imports: [AsyncPipe, CurrencyPipe, DatePipe, NgIf],
  templateUrl: './transaction-history.component.html',
  styleUrl: './transaction-history.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TransactionHistoryComponent {
  @Input()
  isOpen = false;
  @Output()
  closeEventEmitter = new EventEmitter<void>();

  protected offset = 0;

  private transactionService: TransactionService = inject(TransactionService);
  transactionData$: Observable<TransactionData> = this.loadTransactions();

  closeDialog() {
    this.isOpen = false;
    this.closeEventEmitter.emit();
  }

  forward() {
    this.offset++;
    this.transactionData$ = this.loadTransactions();
  }

  back() {
    this.offset--;
    this.transactionData$ = this.loadTransactions();
  }

  loadTransactions() {
    return this.transactionService.getUsersTransactions(PER_PAGE, this.offset * PER_PAGE);
  }
}
