import React from 'react';
import { CheckoutProvider } from '../contexts/CheckoutContext';
import { CheckoutPage } from '../components/checkout/CheckoutPage';
import { useCheckout } from '../contexts/CheckoutContext';
import { useNavigate } from 'react-router-dom';
import { Loading } from '../components/ui/Loading';

const CheckoutContent: React.FC = () => {
  const {
    requester,
    selectedRecipientAccountId,
    selectedRecipientAccount,
    fundRequest,
    transactionFee,
    submitPayment,
  } = useCheckout();
  const navigate = useNavigate();

  const handlePaymentComplete = async () => {
    await submitPayment();
    // After payment, you might want to navigate somewhere or show a success message
  };

  if (!requester || !fundRequest) {
    return <Loading fullScreen message="Loading checkout..." />;
  }

  // Get the selected account from the requester's bank accounts
  const account = selectedRecipientAccount || 
    (selectedRecipientAccountId && requester.bankAccounts?.find(acc => acc.id === selectedRecipientAccountId)) ||
    requester.bankAccounts?.[0];
  
  if (!account) {
    return <Loading fullScreen message="Loading account details..." />;
  }
  
  return (
    <CheckoutPage
      requester={{
        name: requester.name,
        requestAmount: requester.requestAmount,
        description: requester.description,
      }}
      selectedAccount={{
        bankName: account.bankName,
        accountNumber: account.accountNumber,
      }}
      transactionFee={transactionFee}
      onComplete={handlePaymentComplete}
    />
  );
};

export const CheckoutPageRoute: React.FC = () => {
  return (
    <CheckoutProvider>
      <CheckoutContent />
    </CheckoutProvider>
  );
};

