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

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

type PurchaseStatusView = 'approved' | 'pending' | 'rejected' | '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, OnDestroy {
  private readonly route = inject(ActivatedRoute);
  private readonly router = inject(Router);
  private readonly checkoutService = inject(CheckoutService);
  private readonly tenantService = inject(TenantService);

  private readonly pollIntervalMs = 5000;
  private purchaseId: string | null = null;
  private tenantCode: string | null = null;
  private pollTimeoutId: ReturnType<typeof setTimeout> | null = null;

  protected readonly isLoading = signal(true);
  protected readonly isRefreshing = signal(false);
  protected readonly status = signal<PurchaseStatusView>('pending');

  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.refreshStatus(true);
  }

  ngOnDestroy(): void {
    this.clearScheduledPoll();
  }

  protected retryStatusCheck(): void {
    void this.refreshStatus(false);
  }

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

    this.clearScheduledPoll();

    if (showLoader) {
      this.isLoading.set(true);
    } else {
      this.isRefreshing.set(true);
    }

    try {
      const purchase = await this.checkoutService.getPurchase(this.tenantCode, this.purchaseId);
      const resolvedStatus = this.resolveStatus(purchase);

      this.status.set(resolvedStatus);

      if (resolvedStatus === 'pending') {
        this.scheduleNextPoll();
      }
    } catch (error) {
      console.error('Failed to fetch purchase status:', error);
      this.status.set('error');
    } finally {
      this.isLoading.set(false);
      this.isRefreshing.set(false);
    }
  }

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

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

    return 'pending';
  }

  private scheduleNextPoll(): void {
    if (this.pollTimeoutId !== null) {
      return;
    }

    this.pollTimeoutId = setTimeout(() => {
      this.pollTimeoutId = null;
      void this.refreshStatus(false);
    }, this.pollIntervalMs);
  }

  private clearScheduledPoll(): void {
    if (this.pollTimeoutId === null) {
      return;
    }

    clearTimeout(this.pollTimeoutId);
    this.pollTimeoutId = null;
  }

  protected getWhatsAppLink(): string {
    const phone = '5493416658247';
    const message = encodeURIComponent('Hola! Mi compra fue realizada con \u00E9xito.');
    return `https://wa.me/${phone}?text=${message}`;
  }

  protected openWhatsApp(): void {
    window.open(this.getWhatsAppLink(), '_blank', 'noopener,noreferrer');
  }
}
