import { Component, OnInit, inject, signal } from '@angular/core';
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';
import { ApiPaginationMeta } from '../../../../../../core/services/api-paginated-response.interface';
import { PaginatorComponent } from '../../../../../../shared/components/paginator/paginator.component';

type PurchaseListViewModel = {
  id: number;
  date: string;
  statusMessage: string | null;
};

@Component({
  selector: 'app-purchase-list',
  standalone: true,
  imports: [PurchaseListItem, PaginatorComponent],
  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);

  protected readonly purchases = signal<PurchaseListViewModel[]>([]);
  protected readonly pagination = signal<ApiPaginationMeta | null>(null);
  protected readonly isLoading = signal(true);

  async ngOnInit(): Promise<void> {
    await this.loadPurchases();
  }

  protected async onPageChange(page: number): Promise<void> {
    await this.loadPurchases(page);
  }

  private async loadPurchases(page = 1): Promise<void> {
    this.isLoading.set(true);

    try {
      const response = await this.checkoutService
        .withCustomLoading()
        .getPurchases(this.tenantCode(), 'paid,in_review', { page });

      this.purchases.set(this.mapPurchases(response.data));
      this.pagination.set(response.meta);
    } catch (error) {
      this.toastService.danger('Hubo un error al cargar las compras');
    } finally {
      this.isLoading.set(false);
    }
  }

  private tenantCode(): string {
    return this.tenantService.tenant()?.codigo || '';
  }

  private mapPurchases(purchases: PurchaseSummaryResponse[]): PurchaseListViewModel[] {
    return purchases.map((purchase) => ({
      id: purchase.id,
      date: this.formatDate(purchase.created_at),
      statusMessage: purchase.status === 'in_review' ? 'Esperando confirmación' : null,
    }));
  }

  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);
  }
}
