import { Component, OnInit, inject, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PurchaseListItem } from '../purchase-list-item/purchase-list-item';
import { CheckoutService, PurchaseSummaryResponse } from '../../../../../../core/services/checkout.service';
import { ToastService } from '../../../../../../core/services/toast.service';
import { TenantService } from '../../../../../../core/services/tenant.service';

type PurchaseListViewModel = {
  id: number;
  date: string;
};

@Component({
  selector: 'app-purchase-list',
  standalone: true,
  imports: [CommonModule, PurchaseListItem],
  templateUrl: './purchase-list.html',
  styleUrl: './purchase-list.scss',
})
export class PurchaseList implements OnInit {
  private readonly checkoutService = inject(CheckoutService);
  private readonly toastService = inject(ToastService);
  private readonly tenantService = inject(TenantService);

  purchases = signal<PurchaseListViewModel[]>([]);
  isLoading = signal<boolean>(true);

  async ngOnInit(): Promise<void> {
    try {
      const tenantCode = this.tenantService.tenant()?.codigo || '';
      
      const response = await this.checkoutService.getPurchases(tenantCode, 'paid');
      const mappedPurchases = response.data.map((purchase: PurchaseSummaryResponse) => ({
        id: purchase.id,
        date: this.formatDate(purchase.created_at),
      }));
      this.purchases.set(mappedPurchases);
    } catch (error) {
      this.toastService.danger('Hubo un error al cargar las compras');
    } finally {
      this.isLoading.set(false);
    }
  }

  private formatDate(value: string | null): string {
    if (!value) {
      return '-';
    }

    const date = new Date(value);

    if (Number.isNaN(date.getTime())) {
      return '-';
    }

    return new Intl.DateTimeFormat('es-AR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    }).format(date);
  }
}
