// payment-failure.component.ts - Updated version
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';

interface FailedTransactionDetails {
  transactionId: string;
  status: string;
  amount: string;
  customerName: string;
  customerEmail: string;
  customerPhone: string;
  products: string;
  failureReason: string;
  transactionDate: string;
  errorCode?: string;
  errorMessage?: string;
}

@Component({
  selector: 'app-payment-failure',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './payment-failure.component.html',
  styleUrls: ['./payment-failure.component.scss']
})
export class PaymentFailureComponent implements OnInit {
  transactionDetails: FailedTransactionDetails | null = null;
  loading = true;
  error = '';
  originalParams: any;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private http: HttpClient
  ) {}

  ngOnInit() {
    // Get all query parameters from PayU response
    this.route.queryParams.subscribe(params => {
      console.log('PayU Failure Response Parameters:', params);
      this.originalParams = params;
      this.processFailureResponse(params);
    });
  }

  processFailureResponse(params: any) {
    if (!params.txnid) {
      this.error = 'Invalid payment response received';
      this.loading = false;
      return;
    }

    // Process the failure data directly (no backend logging needed for now)
    this.transactionDetails = {
      transactionId: params.txnid,
      status: params.status || 'Failed',
      amount: params.amount || '0.00',
      customerName: `${params.firstname || ''} ${params.lastname || ''}`.trim(),
      customerEmail: params.email || '',
      customerPhone: params.phone || '',
      products: params.productinfo || '',
      failureReason: params.error_Message || params.error || 'Payment processing failed',
      transactionDate: new Date().toLocaleString(),
      errorCode: params.error_code || params.error
    };
    
    this.loading = false;
    
    // Optional: Log to backend in the background (non-blocking)
    this.logFailureInBackground(params);
  }

  logFailureInBackground(params: any) {
    // Optional background logging - won't block the UI if it fails
    this.http.post(`${environment.apiUrl}/log-payment-failure`, params).subscribe({
      next: (response) => {
        console.log('Payment failure logged successfully');
      },
      error: (error) => {
        console.log('Failed to log payment failure (continuing anyway):', error);
        // Don't show error to user - this is just background logging
      }
    });
  }

  retryPayment() {
    // Check if we have pending cart data in session
    const pendingCart = sessionStorage.getItem('pendingCart');
    const pendingMachineId = sessionStorage.getItem('pendingMachineId');
    
    if (pendingMachineId) {
      // Redirect back to the machine with cart intact
      this.router.navigate(['/machine-slots', pendingMachineId]);
    } else if (this.originalParams.udf1) {
      // Use machine ID from UDF1 if available
      this.router.navigate(['/machine-slots', this.originalParams.udf1]);
    } else {
      // Fallback to login page
      this.router.navigate(['/login']);
    }
  }

  goToMachine() {
    // Clear cart and redirect to machine selection
    sessionStorage.removeItem('pendingCart');
    sessionStorage.removeItem('pendingMachineId');
    
    if (this.originalParams.udf1) {
      this.router.navigate(['/machine-slots', this.originalParams.udf1]);
    } else {
      this.router.navigate(['/login']);
    }
  }

  contactSupport() {
    // Create support email with transaction details
    const subject = `Payment Failure - Transaction ID: ${this.transactionDetails?.transactionId}`;
    const body = `Dear Support Team,

I encountered a payment failure with the following details:

Transaction ID: ${this.transactionDetails?.transactionId}
Amount: ₹${this.transactionDetails?.amount}
Status: ${this.transactionDetails?.status}
Error: ${this.transactionDetails?.failureReason}
Date: ${this.transactionDetails?.transactionDate}

Customer Details:
Name: ${this.transactionDetails?.customerName}
Email: ${this.transactionDetails?.customerEmail}
Phone: ${this.transactionDetails?.customerPhone}

Products: ${this.transactionDetails?.products}

Please assist me with this issue.

Thank you.`;

    const mailtoUrl = `mailto:support@yourdomain.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = mailtoUrl;
  }

  getFailureReasonClass(): string {
    if (!this.transactionDetails?.failureReason) return '';
    
    const reason = this.transactionDetails.failureReason.toLowerCase();
    
    if (reason.includes('insufficient') || reason.includes('balance')) return 'insufficient-funds';
    if (reason.includes('timeout') || reason.includes('expired')) return 'timeout';
    if (reason.includes('cancelled') || reason.includes('abort')) return 'cancelled';
    if (reason.includes('network') || reason.includes('connection')) return 'network';
    if (reason.includes('authentication') || reason.includes('invalid')) return 'authentication';
    
    return 'general-error';
  }

  getFailureIcon(): string {
    const reasonClass = this.getFailureReasonClass();
    
    switch (reasonClass) {
      case 'insufficient-funds': return '💳';
      case 'timeout': return '⏱️';
      case 'cancelled': return '❌';
      case 'network': return '🌐';
      case 'authentication': return '🔒';
      default: return '⚠️';
    }
  }
}