'use client';

/**
 * Payment Modal Component
 * Handles payment processing for a sale with split payment support (up to 2 tenders)
 */

import { useState, useEffect, useRef } from 'react';
import { Modal, Button } from '@/components/ui';
import { formatCurrency } from '@/lib/utils/format';
import { PAYMENT_METHODS } from '@/lib/utils/constants';
import { paymentsAPI } from '@/lib/api';
import { CreditCard, Banknote, Smartphone, CheckCircle, ArrowRight, Plus, X, RotateCcw, Clock, AlertCircle } from 'lucide-react';
import toast from 'react-hot-toast';

const paymentMethods = [
  { value: PAYMENT_METHODS.CASH, label: 'Cash', icon: Banknote, color: 'from-green-500 to-emerald-600' },
  { value: PAYMENT_METHODS.PAYSTACK, label: 'Card', icon: CreditCard, color: 'from-blue-500 to-indigo-600' },
  { value: PAYMENT_METHODS.MOBILE_MONEY, label: 'Mobile', icon: Smartphone, color: 'from-purple-500 to-pink-600' },
];

// Quick cash amounts for faster checkout
const quickAmounts = [100, 200, 500, 1000, 2000, 5000];

export default function PaymentModal({
  isOpen,
  onClose,
  total,
  onPaymentComplete,
  saleId,
  onManualMPesaConfirm = null, // Callback to open manual M-Pesa confirmation modal
}) {
  const [payments, setPayments] = useState([
    { method: PAYMENT_METHODS.CASH, amount: '', card_reference: '', phone_number: '' },
  ]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [stkPushStatus, setStkPushStatus] = useState({}); // { paymentIndex: { checkoutRequestID, status, countdown, etc } }
  const pollingIntervals = useRef({});
  const countdownTimers = useRef({});

  // Cleanup on unmount or modal close
  useEffect(() => {
    return () => {
      // Clear all polling intervals
      Object.values(pollingIntervals.current).forEach(interval => clearInterval(interval));
      Object.values(countdownTimers.current).forEach(timer => clearInterval(timer));
      pollingIntervals.current = {};
      countdownTimers.current = {};
    };
  }, []);

  // Clear statuses when modal closes
  useEffect(() => {
    if (!isOpen) {
      setStkPushStatus({});
      Object.values(pollingIntervals.current).forEach(interval => clearInterval(interval));
      Object.values(countdownTimers.current).forEach(timer => clearInterval(timer));
      pollingIntervals.current = {};
      countdownTimers.current = {};
    }
  }, [isOpen]);

  // Reset payments when modal opens
  useEffect(() => {
    if (isOpen) {
      setPayments([{ method: PAYMENT_METHODS.CASH, amount: total.toString(), card_reference: '', phone_number: '' }]);
    }
  }, [isOpen, total]);

  // Calculate totals
  const paidAmounts = payments.map(p => parseFloat(p.amount) || 0);
  const totalPaid = paidAmounts.reduce((sum, amt) => sum + amt, 0);
  const remaining = total - totalPaid;
  const isValid = remaining === 0 && payments.length > 0 && payments.every(p => {
    const amt = parseFloat(p.amount) || 0;
    return amt > 0 && (
      p.method !== PAYMENT_METHODS.PAYSTACK || p.card_reference.trim() !== ''
    ) && (
      p.method !== PAYMENT_METHODS.MOBILE_MONEY || p.phone_number.trim() !== ''
    );
  });

  // Handle payment method change
  const handleMethodChange = (index, method) => {
    const updated = [...payments];
    updated[index] = { ...updated[index], method, amount: index === 0 && updated.length === 1 ? total.toString() : updated[index].amount };
    setPayments(updated);
  };

  // Handle amount change
  const handleAmountChange = (index, amount) => {
    const updated = [...payments];
    updated[index] = { ...updated[index], amount };
    setPayments(updated);
  };

  // Handle card reference change
  const handleCardReferenceChange = (index, card_reference) => {
    const updated = [...payments];
    updated[index] = { ...updated[index], card_reference };
    setPayments(updated);
  };

  // Handle phone number change
  const handlePhoneChange = (index, phone_number) => {
    const updated = [...payments];
    updated[index] = { ...updated[index], phone_number };
    setPayments(updated);
  };

  // Add second payment
  const handleAddPayment = () => {
    if (payments.length < 2) {
      setPayments([...payments, { method: PAYMENT_METHODS.CASH, amount: remaining.toString(), card_reference: '', phone_number: '' }]);
    }
  };

  // Remove payment
  const handleRemovePayment = (index) => {
    if (payments.length > 1) {
      const updated = payments.filter((_, i) => i !== index);
      // If removing first payment, update second payment amount
      if (index === 0 && updated.length > 0) {
        updated[0].amount = total.toString();
      }
      setPayments(updated);
    }
  };

  // Start polling for STK Push status
  const startSTKPushPolling = (paymentIndex, checkoutRequestID, timeoutSeconds = 60) => {
    // Clear existing interval for this payment
    if (pollingIntervals.current[paymentIndex]) {
      clearInterval(pollingIntervals.current[paymentIndex]);
    }
    if (countdownTimers.current[paymentIndex]) {
      clearInterval(countdownTimers.current[paymentIndex]);
    }

    // Set countdown timer
    let countdown = timeoutSeconds;
    setStkPushStatus(prev => ({
      ...prev,
      [paymentIndex]: {
        ...prev[paymentIndex],
        checkoutRequestID,
        status: 'pending',
        countdown,
        customerMessage: 'Waiting for customer to complete payment...',
      },
    }));

    countdownTimers.current[paymentIndex] = setInterval(() => {
      countdown -= 1;
      setStkPushStatus(prev => ({
        ...prev,
        [paymentIndex]: {
          ...prev[paymentIndex],
          countdown,
        },
      }));

      if (countdown <= 0) {
        clearInterval(countdownTimers.current[paymentIndex]);
        setStkPushStatus(prev => ({
          ...prev,
          [paymentIndex]: {
            ...prev[paymentIndex],
            status: 'timeout',
          },
        }));
      }
    }, 1000);

    // Poll for status every 3 seconds
    pollingIntervals.current[paymentIndex] = setInterval(async () => {
      try {
        const response = await paymentsAPI.querySTKPushStatus(checkoutRequestID);
        const queryResult = response.data?.queryResult || response.queryResult;
        const paymentStatus = response.data?.payment || response.payment;

        if (queryResult.isComplete) {
          // Payment completed
          clearInterval(pollingIntervals.current[paymentIndex]);
          clearInterval(countdownTimers.current[paymentIndex]);
          setStkPushStatus(prev => ({
            ...prev,
            [paymentIndex]: {
              ...prev[paymentIndex],
              status: 'success',
              mpesaReceiptNumber: queryResult.mpesaReceiptNumber,
            },
          }));

          // Check if all payments are complete
          checkAllPaymentsComplete();
        } else if (queryResult.isPending) {
          // Still pending
          setStkPushStatus(prev => ({
            ...prev,
            [paymentIndex]: {
              ...prev[paymentIndex],
              status: 'pending',
            },
          }));
        } else {
          // Failed
          clearInterval(pollingIntervals.current[paymentIndex]);
          clearInterval(countdownTimers.current[paymentIndex]);
          setStkPushStatus(prev => ({
            ...prev,
            [paymentIndex]: {
              ...prev[paymentIndex],
              status: 'failed',
              error: queryResult.resultDesc,
            },
          }));
        }
      } catch (error) {
        console.error('STK Push status query error:', error);
      }
    }, 3000); // Poll every 3 seconds

    // Stop polling after timeout
    setTimeout(() => {
      if (pollingIntervals.current[paymentIndex]) {
        clearInterval(pollingIntervals.current[paymentIndex]);
      }
    }, timeoutSeconds * 1000);
  };

  // Check if all payments are complete
  const checkAllPaymentsComplete = () => {
    const allComplete = Object.values(stkPushStatus).every(status => 
      status.status === 'success'
    ) && payments.every((payment, index) => 
      payment.method === PAYMENT_METHODS.CASH || 
      payment.method === PAYMENT_METHODS.PAYSTACK || 
      stkPushStatus[index]?.status === 'success'
    );

    if (allComplete) {
      setTimeout(() => {
        toast.success('All payments completed successfully!');
        onPaymentComplete(payments);
        onClose();
      }, 1500);
    }
  };

  // Retry STK Push
  const handleRetrySTKPush = async (paymentIndex) => {
    const payment = payments[paymentIndex];
    if (!payment.phone_number || !payment.amount) {
      toast.error('Please enter phone number and amount');
      return;
    }

    setIsProcessing(true);
    try {
      const paymentData = {
        sale_id: saleId,
        amount: parseFloat(payment.amount),
        provider: PAYMENT_METHODS.MOBILE_MONEY,
        mpesa_phone_number: payment.phone_number,
      };

      const response = await paymentsAPI.create(paymentData);
      const checkoutRequestID = response.data?.stkPush?.checkoutRequestID || 
                                 response.data?.payment?.reference ||
                                 response.stkPush?.checkoutRequestID;

      if (checkoutRequestID) {
        startSTKPushPolling(paymentIndex, checkoutRequestID);
        toast.success('Payment request sent! Please check your phone.');
      }
    } catch (error) {
      toast.error(error.message || 'Failed to retry payment');
    } finally {
      setIsProcessing(false);
    }
  };

  // Process payments
  const handleProcessPayments = async () => {
    if (!saleId) {
      toast.error('Sale not created. Please try again.');
      return;
    }

    if (!isValid) {
      toast.error('Please complete all payment information correctly.');
      return;
    }

    setIsProcessing(true);
    try {
      // Process each payment sequentially
      const processedPayments = [];
      for (let i = 0; i < payments.length; i++) {
        const payment = payments[i];
        
        // Cash and Card payments are immediate
        if (payment.method === PAYMENT_METHODS.CASH || payment.method === PAYMENT_METHODS.PAYSTACK) {
          const paymentData = {
            sale_id: saleId,
            amount: parseFloat(payment.amount),
            provider: payment.method,
            ...(payment.method === PAYMENT_METHODS.PAYSTACK && payment.card_reference && {
              card_reference: payment.card_reference,
            }),
          };

          const response = await paymentsAPI.create(paymentData);
          const paymentResult = response.data || response;
          
          if (paymentResult) {
            processedPayments.push(paymentResult);
            
            // Check if sale was updated to PAID
            if (paymentResult.sale?.status === 'PAID') {
              console.log(`✅ Sale ${saleId} marked as PAID after payment`);
            } else {
              console.warn(`⚠️ Sale ${saleId} status: ${paymentResult.sale?.status || 'unknown'}. Expected PAID after cash payment.`);
            }
          }
        }
        // M-Pesa payments require STK Push
        else if (payment.method === PAYMENT_METHODS.MOBILE_MONEY) {
          const paymentData = {
            sale_id: saleId,
            amount: parseFloat(payment.amount),
            provider: PAYMENT_METHODS.MOBILE_MONEY,
            mpesa_phone_number: payment.phone_number,
          };

          const response = await paymentsAPI.create(paymentData);
          const result = response.data || response;
          
          if (result.payment) {
            processedPayments.push(result.payment);
          }

          // Check for STK Push errors
          if (result.stkPush?.error) {
            if (result.stkPush.configurationError) {
              toast.error('M-Pesa is not configured. Please contact system administrator.', { duration: 5000 });
            } else {
              toast.error(result.stkPush.message || 'Failed to initiate payment request. Payment created but STK Push failed.', { duration: 5000 });
            }
            // Don't start polling if there's an error
          } else {
            // Start STK Push polling
            const checkoutRequestID = result.stkPush?.checkoutRequestID || result.payment?.reference;
            if (checkoutRequestID) {
              startSTKPushPolling(i, checkoutRequestID, 60);
              toast.success(`Payment request sent to ${payment.phone_number}! Please check your phone.`, { duration: 3000 });
            }
          }
        }
      }

      // Check if we have any successful STK Push requests or no M-Pesa payments at all
      const hasMpesaPayments = payments.some(p => p.method === PAYMENT_METHODS.MOBILE_MONEY);
      const hasSuccessfulSTKPush = processedPayments.some(p => {
        // Check if there's a pending STK Push polling for this payment
        return Object.keys(stkPushStatus).length > 0;
      });
      
      if (!hasMpesaPayments || !hasSuccessfulSTKPush) {
        // No M-Pesa payments or all STK Push requests failed - close modal
        if (processedPayments.length > 0) {
          toast.success(`Payment${processedPayments.length > 1 ? 's' : ''} processed successfully!`);
        }
        onPaymentComplete(processedPayments);
        onClose();
      } else {
        // Keep modal open for STK Push status tracking
        setIsProcessing(false);
      }
    } catch (error) {
      toast.error(error.message || 'Payment processing error');
      console.error('Payment error:', error);
      setIsProcessing(false);
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Process Payment"
      size="xl"
    >
      <div className="p-6 space-y-6">
        {/* Total Amount Display */}
        <div className="bg-gradient-to-r from-gray-900 to-gray-800 dark:from-gray-800 dark:to-gray-700 rounded-2xl p-6 text-center">
          <p className="text-gray-400 text-sm font-medium mb-1">Total Amount Due</p>
          <p className="text-4xl font-bold text-white">
            {formatCurrency(total)}
          </p>
        </div>

        {/* Payments List */}
        <div className="space-y-4">
          {payments.map((payment, index) => {
            const paymentAmount = parseFloat(payment.amount) || 0;
            const change = payment.method === PAYMENT_METHODS.CASH && paymentAmount > (index === 0 ? total : remaining + paymentAmount) - paymentAmount
              ? paymentAmount - ((index === 0 ? total : remaining + paymentAmount) - paymentAmount)
              : 0;

            return (
              <div key={index} className="border-2 border-gray-200 dark:border-gray-700 rounded-xl p-4 space-y-4">
                {/* Payment Header */}
                <div className="flex items-center justify-between">
                  <h3 className="font-semibold text-lg text-gray-900 dark:text-white">
                    Payment {index + 1} {payments.length > 1 && `of ${payments.length}`}
                  </h3>
                  {payments.length > 1 && (
                    <button
                      onClick={() => handleRemovePayment(index)}
                      className="p-2 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                    >
                      <X className="w-5 h-5" />
                    </button>
                  )}
                </div>

                {/* Payment Method Selection */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                    Payment Method
                  </label>
                  <div className="grid grid-cols-3 gap-3">
                    {paymentMethods.map((method) => {
                      const Icon = method.icon;
                      const isSelected = payment.method === method.value;
                      return (
                        <button
                          key={method.value}
                          onClick={() => handleMethodChange(index, method.value)}
                          className={`
                            relative p-4 rounded-xl border-2 transition-all duration-200
                            ${isSelected 
                              ? 'border-transparent bg-gradient-to-r ' + method.color + ' text-white shadow-lg scale-[1.02]'
                              : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:border-gray-300 dark:hover:border-gray-600'
                            }
                          `}
                        >
                          <Icon className={`w-8 h-8 mx-auto mb-2 ${isSelected ? 'text-white' : 'text-gray-400'}`} />
                          <p className="font-semibold text-sm">{method.label}</p>
                          {isSelected && (
                            <CheckCircle className="absolute top-2 right-2 w-5 h-5 text-white" />
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>

                {/* Cash Payment Input */}
                {payment.method === PAYMENT_METHODS.CASH && (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Amount Received
                      </label>
                      <div className="relative">
                        <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 font-medium">
                          Ksh
                        </span>
                        <input
                          type="number"
                          step="0.01"
                          value={payment.amount}
                          onChange={(e) => handleAmountChange(index, e.target.value)}
                          className="w-full pl-14 pr-4 py-4 text-2xl font-bold rounded-xl border-2 transition-all bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 border-gray-300 dark:border-gray-600"
                        />
                      </div>
                    </div>

                    {/* Quick Amount Buttons */}
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Quick Amounts
                      </label>
                      <div className="grid grid-cols-3 gap-2">
                        {quickAmounts.map((quickAmount) => (
                          <button
                            key={quickAmount}
                            onClick={() => handleAmountChange(index, quickAmount.toString())}
                            className={`py-3 px-4 rounded-xl font-semibold transition-all duration-200 ${
                              parseFloat(payment.amount) === quickAmount
                                ? 'bg-blue-600 text-white shadow-lg'
                                : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
                            }`}
                          >
                            {formatCurrency(quickAmount)}
                          </button>
                        ))}
                      </div>
                      <button
                        onClick={() => handleAmountChange(index, (index === 0 ? total : remaining).toString())}
                        className="w-full mt-2 py-3 px-4 rounded-xl font-semibold bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-400 hover:bg-emerald-200 dark:hover:bg-emerald-900/50 transition-all"
                      >
                        Exact Amount ({formatCurrency(index === 0 ? total : remaining)})
                      </button>
                    </div>

                    {/* Change Display */}
                    {change > 0 && (
                      <div className="bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-900/20 dark:to-emerald-900/20 border-2 border-green-200 dark:border-green-800 rounded-xl p-4">
                        <div className="flex justify-between items-center">
                          <span className="text-green-700 dark:text-green-400 font-medium">Change Due</span>
                          <span className="text-2xl font-bold text-green-700 dark:text-green-400">
                            {formatCurrency(change)}
                          </span>
                        </div>
                      </div>
                    )}
                  </div>
                )}

                {/* Card Payment Input */}
                {payment.method === PAYMENT_METHODS.PAYSTACK && (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Amount
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        value={payment.amount}
                        onChange={(e) => handleAmountChange(index, e.target.value)}
                        className="w-full px-4 py-3 text-xl font-bold rounded-xl border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Card Reference / Transaction ID *
                      </label>
                      <input
                        type="text"
                        value={payment.card_reference}
                        onChange={(e) => handleCardReferenceChange(index, e.target.value)}
                        placeholder="Enter card transaction reference"
                        className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter the card transaction reference number
                      </p>
                    </div>
                  </div>
                )}

                {/* Mobile Money Payment Input */}
                {payment.method === PAYMENT_METHODS.MOBILE_MONEY && (
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Amount
                      </label>
                      <input
                        type="number"
                        step="0.01"
                        value={payment.amount}
                        onChange={(e) => handleAmountChange(index, e.target.value)}
                        disabled={!!stkPushStatus[index]?.checkoutRequestID}
                        className="w-full px-4 py-3 text-xl font-bold rounded-xl border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Phone Number *
                      </label>
                      <input
                        type="tel"
                        value={payment.phone_number}
                        onChange={(e) => handlePhoneChange(index, e.target.value)}
                        placeholder="0712345678 or +254712345678"
                        disabled={!!stkPushStatus[index]?.checkoutRequestID}
                        className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                      />
                      <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Enter M-Pesa phone number (0712345678 or +254712345678)
                      </p>
                    </div>

                    {/* STK Push Status Display */}
                    {stkPushStatus[index] && (
                      <div className={`
                        rounded-xl p-4 border-2
                        ${stkPushStatus[index].status === 'success' 
                          ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800'
                          : stkPushStatus[index].status === 'timeout' || stkPushStatus[index].status === 'failed'
                          ? 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800'
                          : 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800'
                        }
                      `}>
                        {stkPushStatus[index].status === 'pending' && (
                          <div className="space-y-3">
                            <div className="flex items-center gap-3">
                              <Clock className="w-5 h-5 text-blue-600 dark:text-blue-400 animate-spin" />
                              <div className="flex-1">
                                <p className="font-semibold text-blue-700 dark:text-blue-400">
                                  {stkPushStatus[index].customerMessage || 'Waiting for customer...'}
                                </p>
                                {stkPushStatus[index].countdown > 0 && (
                                  <p className="text-sm text-blue-600 dark:text-blue-400 mt-1">
                                    Time remaining: {stkPushStatus[index].countdown}s
                                  </p>
                                )}
                              </div>
                            </div>
                          </div>
                        )}

                        {stkPushStatus[index].status === 'success' && (
                          <div className="flex items-center gap-3">
                            <CheckCircle className="w-5 h-5 text-green-600 dark:text-green-400" />
                            <div className="flex-1">
                              <p className="font-semibold text-green-700 dark:text-green-400">
                                Payment Confirmed!
                              </p>
                              {stkPushStatus[index].mpesaReceiptNumber && (
                                <p className="text-sm text-green-600 dark:text-green-400 mt-1 font-mono">
                                  Receipt: {stkPushStatus[index].mpesaReceiptNumber}
                                </p>
                              )}
                            </div>
                          </div>
                        )}

                        {(stkPushStatus[index].status === 'timeout' || stkPushStatus[index].status === 'failed') && (
                          <div className="space-y-3">
                            <div className="flex items-center gap-3">
                              <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400" />
                              <div className="flex-1">
                                <p className="font-semibold text-red-700 dark:text-red-400">
                                  {stkPushStatus[index].status === 'timeout' ? 'Payment Timeout' : 'Payment Failed'}
                                </p>
                                {stkPushStatus[index].error && (
                                  <p className="text-sm text-red-600 dark:text-red-400 mt-1">
                                    {stkPushStatus[index].error}
                                  </p>
                                )}
                              </div>
                            </div>
                            <div className="flex gap-2">
                              <Button
                                variant="primary"
                                size="sm"
                                onClick={() => handleRetrySTKPush(index)}
                                className="flex items-center gap-2"
                                disabled={isProcessing}
                                loading={isProcessing}
                              >
                                <RotateCcw className="w-4 h-4" />
                                Retry STK Push
                              </Button>
                              <Button
                                variant="outline"
                                  size="sm"
                                  onClick={() => {
                                    if (onManualMPesaConfirm) {
                                      // Get payment ID - we need to track it from the payment creation response
                                      // For now, try to find it from processed payments or use checkoutRequestID to look it up
                                      const checkoutRequestID = stkPushStatus[index]?.checkoutRequestID;
                                      if (checkoutRequestID) {
                                        // The parent component should handle fetching the payment ID
                                        onManualMPesaConfirm(checkoutRequestID);
                                      } else {
                                        onManualMPesaConfirm(null);
                                      }
                                    } else {
                                      toast('Customer should pay via M-Pesa Paybill. Ask for transaction code after payment.', { duration: 5000 });
                                    }
                                  }}
                                >
                                  {onManualMPesaConfirm ? "Manual Confirm" : "Use C2B (Manual)"}
                                </Button>
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* Add Second Payment Button */}
        {payments.length < 2 && totalPaid < total && (
          <button
            onClick={handleAddPayment}
            className="w-full py-3 px-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-xl text-gray-600 dark:text-gray-400 hover:border-blue-500 dark:hover:border-blue-400 hover:text-blue-600 dark:hover:text-blue-400 transition-all flex items-center justify-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Add Second Payment Method
          </button>
        )}

        {/* Payment Summary */}
        <div className="bg-gray-50 dark:bg-gray-800 rounded-xl p-4 space-y-2">
          <div className="flex justify-between text-sm">
            <span className="text-gray-600 dark:text-gray-400">Total Due:</span>
            <span className="font-semibold text-gray-900 dark:text-white">{formatCurrency(total)}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-600 dark:text-gray-400">Total Paid:</span>
            <span className={`font-semibold ${totalPaid >= total ? 'text-green-600 dark:text-green-400' : 'text-gray-900 dark:text-white'}`}>
              {formatCurrency(totalPaid)}
            </span>
          </div>
          {remaining > 0 && (
            <div className="flex justify-between text-sm pt-2 border-t border-gray-200 dark:border-gray-700">
              <span className="text-amber-600 dark:text-amber-400 font-medium">Remaining:</span>
              <span className="font-bold text-amber-600 dark:text-amber-400">{formatCurrency(remaining)}</span>
            </div>
          )}
          {remaining === 0 && (
            <div className="flex justify-between text-sm pt-2 border-t border-green-200 dark:border-green-800">
              <span className="text-green-600 dark:text-green-400 font-medium">Status:</span>
              <span className="font-bold text-green-600 dark:text-green-400">Fully Paid ✓</span>
            </div>
          )}
        </div>

        {/* Action Buttons */}
        <div className="flex gap-3 pt-4">
          <Button
            variant="outline"
            onClick={onClose}
            className="flex-1 py-4"
            disabled={isProcessing}
          >
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleProcessPayments}
            className="flex-1 py-4 bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700"
            disabled={isProcessing || !isValid}
            loading={isProcessing}
          >
            {isProcessing ? (
              'Processing...'
            ) : (
              <>
                Complete Payment{payments.length > 1 ? 's' : ''}
                <ArrowRight className="w-5 h-5 ml-2" />
              </>
            )}
          </Button>
        </div>
      </div>
    </Modal>
  );
}
