import { Component, OnInit, computed, 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 { ButtonComponent } from '../../../../../../shared/components/button/button.component';
import { MenuContentSectionComponent } from '../../../../components/menu-content-section/menu-content-section.component';
import { PurchaseItem, PurchaseItemViewModel } from '../../components/purchase-item/purchase-item';

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

@Component({
  selector: 'app-purchase-detail-page',
  standalone: true,
  imports: [RouterLink, PurchaseItem, MenuContentSectionComponent, ButtonComponent],
  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);
  protected readonly whatsappUrl = computed(
    () =>
      this.tenantService
        .tenant()
        ?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? 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
        .withCustomLoading()
        .getPurchase(tenant.codigo, purchaseId);

      this.purchase.set({
        id: response.id,
        date: this.formatDate(response.created_at),
        total: response.total,
        items: this.mapItems(response),
        isInReview: response.status === 'in_review',
      });
    } 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);
    }
  }

  protected openWhatsApp(): void {
    const url = this.whatsappUrl();

    if (url) {
      window.open(url, '_blank', 'noopener,noreferrer');
    }
  }

  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.item_details.nombre || 'Producto sin nombre',
      description: item.item_details.descripcion,
      imageUrl: item.item_details.imagen,
      quantity: item.quantity,
      attributes: item.item_details.attributes.map((attribute) => ({
        label: attribute.name,
        value: attribute.value === null ? null : String(attribute.value),
      })),
      price: item.line_total,
      originalPrice: null,
      transferPrice: null,
      discountPercentage: null,
    }));
  }
}
