import { ChangeDetectionStrategy, Component, OnInit, computed, inject, signal } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { CheckoutService, PurchaseStatusResponse } from '../../../../core/services/checkout.service';
import { findMenu } from '../../../../core/services/menu.utils';
import { TenantService } from '../../../../core/services/tenant.service';
import { ButtonComponent } from '../../../../shared/components/button/button.component';

type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | 'expired' | 'error';

@Component({
  selector: 'app-purchase-status-page',
  standalone: true,
  imports: [ButtonComponent],
  templateUrl: './purchase-status-page.component.html',
  styleUrl: './purchase-status-page.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PurchaseStatusPageComponent implements OnInit {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly checkoutService = inject(CheckoutService);
  private readonly tenantService = inject(TenantService);

  private purchaseId: string | null = null;
  private tenantCode: string | null = null;

  protected readonly isLoading = signal(true);
  protected readonly status = signal<PurchaseStatusView>('pending');
  protected readonly hasGeneratedTickets = signal(false);
  protected readonly ticketsRoute = computed(() => {
    if (!this.hasGeneratedTickets()) {
      return null;
    }

    return findMenu(this.tenantService.tenant()?.menues ?? [], 'account.tickets')?.route ?? null;
  });
  protected readonly whatsappUrl = computed(
    () =>
      this.tenantService
        .tenant()
        ?.social_media?.find((socialMedia) => socialMedia.code === 'whatsapp')?.url ?? null,
  );

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

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

    this.purchaseId = purchaseId;
    this.tenantCode = tenant.codigo;

    void this.loadStatus();
  }

  private async loadStatus(): Promise<void> {
    if (!this.purchaseId || !this.tenantCode) {
      return;
    }

    try {
      const purchase = await this.checkoutService
        .withCustomLoading()
        .getPurchase(this.tenantCode, this.purchaseId);
      this.status.set(this.resolveStatus(purchase));
      this.hasGeneratedTickets.set(purchase.has_generated_tickets === true);
    } catch (error) {
      console.error('Failed to fetch purchase status:', error);
      this.status.set('error');
    } finally {
      this.isLoading.set(false);
    }
  }

  private resolveStatus(purchase: PurchaseStatusResponse): PurchaseStatusView {
    if (purchase.status === 'paid') {
      return 'approved';
    }

    if (purchase.status === 'rejected' || purchase.status === 'cancelled') {
      return 'rejected';
    }

    if (purchase.status === 'expired') {
      return 'expired';
    }

    return 'pending';
  }

  protected goToTickets(): void {
    const route = this.ticketsRoute();

    if (route) {
      void this.router.navigateByUrl(route);
    }
  }

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

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