import { CommonModule } from '@angular/common';
import { Component, OnInit, inject, signal } from '@angular/core';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';

import { CheckoutService, PurchaseDetailResponse } from '../../../../../../core/services/checkout.service';
import { TenantService } from '../../../../../../core/services/tenant.service';
import { ToastService } from '../../../../../../core/services/toast.service';
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';

type PurchaseDetailViewModel = {
  id: number;
  date: string;
  total: string;
  items: PurchaseItemViewModel[];
};

@Component({
  selector: 'app-purchase-detail-page',
  standalone: true,
  imports: [CommonModule, RouterLink, PurchaseItem],
  templateUrl: './purchase-detail-page.html',
  styleUrl: './purchase-detail-page.scss',
})
export class PurchaseDetailPage implements OnInit {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly checkoutService = inject(CheckoutService);
  private readonly tenantService = inject(TenantService);
  private readonly toastService = inject(ToastService);

  readonly isLoading = signal(true);
  readonly purchase = signal<PurchaseDetailViewModel | null>(null);

  async ngOnInit(): Promise<void> {
    const purchaseId = this.route.snapshot.paramMap.get('id');
    const tenant = this.tenantService.tenant();

    if (!purchaseId || !tenant) {
      void this.router.navigate(['/mi-cuenta/compras']);
      return;
    }

    try {
      const response = await this.checkoutService.getPurchase(tenant.codigo, purchaseId);

      this.purchase.set({
        id: response.id,
        date: this.formatDate(response.created_at),
        total: response.total,
        items: this.mapItems(response),
      });
    } catch (error) {
      console.error('Failed to fetch purchase detail:', error);
      this.toastService.danger('Hubo un error al cargar el detalle de la compra');
      void this.router.navigate(['/mi-cuenta/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);
  }

  private mapItems(purchase: PurchaseDetailResponse): PurchaseItemViewModel[] {
    return purchase.items.map((item) => ({
      id: item.id,
      title: item.product?.nombre ?? 'Producto sin nombre',
      imageUrl: item.product?.imagen ?? null,
      quantity: item.quantity,
      attributes: (item.variant?.attributes ?? []).map((attribute) => ({
        label: attribute.name,
        value: attribute.value,
      })),
      price: item.line_total,
      originalPrice: null,
      transferPrice: null,
      discountPercentage: null,
    }));
  }
}
