'use client';

import { useState, useRef, useTransition, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { PaymentChannel } from "../types/channel.types";
import { Organization } from "@/types/organization/organization";
import { minTopupByCurrency, predefinedAmountsByCurrency } from "../const/const";
import { EWalletPage, OTCPage, QRPage, VirtualAccountPage } from "./pages";
import BackButton from "@/components/ui/buttons-group/ButtonBack";
import { Typography } from "@/components/atoms/typogrpahy";
import Button from "@/components/ui/button/Button";
import { Modal } from "@/components/ui/modal";
import { handlePaymentResult } from "../services/paymentHandlers";
import { createTopUp } from '../actions/topup.action';
import {
  buildMidtransTopupFormData,
  buildXenditTopupFormData,
} from '../actions/topupPaymentHelpers';
import { currencyToLocaleString, currencyToSymbol } from "@/lib/transactionUtil";
import { PayPalButton } from './PayPalButton';
import { CreditCardForm } from './CreditCardForm';
import type { XenditCardDetails } from './creditCardFormXendit';
import { ClientOnly } from '@/components/common/ClientOnly';
import { getPaymentProvider, getCreditCardProvider } from '../services/creditCardProvider';
import { getPaymentMethodDisplayName } from '../services/paymentMethodLabel';

interface TopUpFormProps {
  paymentChannels: PaymentChannel[];
  organization?: Organization | null;
}

export const TopUpForm: React.FC<TopUpFormProps> = ({ paymentChannels, organization }) => {
  const router = useRouter();

  // All hooks must be called before any early returns
  const [amount, setAmount] = useState<number>(0);
  const [isConfirmModalOpen, setIsConfirmModalOpen] = useState(false);
  const formRef = useRef<HTMLFormElement>(null);
  const amountInputRef = useRef<HTMLInputElement>(null);
  const [isPending, startTransition] = useTransition();

  const [vaNumber, setVaNumber] = useState<string>('');
  const [vaBankName, setVaBankName] = useState<string>('');
  const [otcCode, setOtcCode] = useState<string>('');
  const [merchantId, setMerchantId] = useState<string>('');
  const [otcExpiresAt, setOtcExpiresAt] = useState<string>('');
  const [qrString, setQrString] = useState<string>('');
  const [redirectUrl, setRedirectUrl] = useState<string>('');
  const [deeplinkUrl, setDeeplinkUrl] = useState<string>('');
  const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
  const [mobileNumber, setMobileNumber] = useState<string>('');
  
  const [paypalTransactionData, setPaypalTransactionData] = useState<{ data?: { id?: string } } | null>(null);
  
  const [creditCardTransactionData, setCreditCardTransactionData] = useState<{ 
    data?: { 
      id?: string; 
      details?: {
        payment_session_id?: string;
        provider?: 'MIDTRANS' | 'XENDIT';
        client_key?: string;
      };
      redirect_url?: string;
      payment_token_id?: string;
      gateway_id?: string;
    } 
  } | null>(null);
  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<PaymentChannel | null>(null);
  const [displayAmount, setDisplayAmount] = useState<string>('0');
  const [amountError, setAmountError] = useState<string | null>(null);
  const [currentView, setCurrentView] = useState<ViewState>('form');
  const [shouldShakeError, setShouldShakeError] = useState(false);
  const shakeTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const didInitAmountRef = useRef(false);

  // Early return after all hooks but before other logic
  if (!organization?.currency) {
    console.error('No currency found for organization');
    return null;
  }

  // Initialize with organization currency 
  const currency = organization.currency;
  const predefinedAmounts = predefinedAmountsByCurrency[currency] || [50000];
  const minTopupAmount = minTopupByCurrency[currency] || predefinedAmounts[0];
  const appMode = (process.env.NEXT_PUBLIC_MODE || process.env.NODE_ENV || '').toLowerCase();
  const enforceMinTopup = appMode === 'production';
  const isBelowMin = enforceMinTopup && amount > 0 && amount < minTopupAmount;

  const validateMinTopup = (value: number) => {
    if (!enforceMinTopup) {
      setAmountError(null);
      return;
    }
    if (value > 0 && value < minTopupAmount) {
      setAmountError(`Minimum topup allowed is ${currencyToSymbol(currency)} ${minTopupAmount.toLocaleString(currencyToLocaleString(currency))}`);
      return;
    }
    setAmountError(null);
  };

  // Initialize amount and displayAmount after we have predefinedAmounts
  useEffect(() => {
    if (!didInitAmountRef.current && predefinedAmounts && predefinedAmounts.length > 0) {
      setAmount(predefinedAmounts[0]);
      setDisplayAmount(predefinedAmounts[0].toLocaleString(currencyToLocaleString(currency)));
      didInitAmountRef.current = true;
    }
  }, [predefinedAmounts, amount, currency]);

  useEffect(() => {
    return () => {
      if (shakeTimeoutRef.current) {
        clearTimeout(shakeTimeoutRef.current);
      }
    };
  }, []);

  const organizedPaymentMethods = useMemo(() => {
      const virtualAccount: PaymentChannel[] = [];
      const eWallet: PaymentChannel[] = [];
      const creditCard: PaymentChannel[] = [];
      const otc: PaymentChannel[] = [];
      const qr: PaymentChannel[] = [];

      paymentChannels.forEach(method => {
        switch (method.type) {
          case 'VIRTUAL_ACCOUNT':
            virtualAccount.push(method);
            break;
          case 'EWALLET':
            eWallet.push(method);
            break;
          case 'CREDIT_CARD':
            creditCard.push(method);
            break;
          case 'OTC':
            otc.push(method);
            break;
          case 'QR':
            qr.push(method);
            break;
          default:
            break;
        }
      });

    // Sort each group by name
    virtualAccount.sort((a, b) => a.name.localeCompare(b.name));
    eWallet.sort((a, b) => {
      const aName = a.name.trim();
      const bName = b.name.trim();
      const aIsGoPay = aName.toLowerCase() === 'gopay';
      const bIsGoPay = bName.toLowerCase() === 'gopay';
      if (aIsGoPay && !bIsGoPay) return -1;
      if (!aIsGoPay && bIsGoPay) return 1;
      return aName.localeCompare(bName);
    });
    creditCard.sort((a, b) => a.name.localeCompare(b.name));
    otc.sort((a, b) => a.name.localeCompare(b.name));
    qr.sort((a, b) => a.name.localeCompare(b.name));

    return [
      { title: 'Virtual Account', methods: virtualAccount },
      { title: 'E-Wallet', methods: eWallet },
      { title: 'Credit Card', methods: creditCard },
      { title: 'QR Payment', methods: qr },
      { title: 'Retail Outlet (OTC)', methods: otc },
    ].filter(group => group.methods.length > 0);
  }, [paymentChannels]);


  const creditCardGroup = organizedPaymentMethods.find(
    (group) => group.title === 'Credit Card'
  );
  const qrGroup = organizedPaymentMethods.find(
    (group) => group.title === 'QR Payment'
  );
  const shouldRenderCardQrRow = Boolean(
    creditCardGroup?.methods.length === 1 && qrGroup?.methods.length === 1
  );

  const getPaymentMethodImageUrl = (method: PaymentChannel): string => {
    return method.logo_url?.trim() || "";
  };

  const getPaymentMethodProviderLabel = (method: PaymentChannel): string | undefined => {
    const provider = getPaymentProvider(method.gateway_id, method.gateway_code);

    return provider === 'MIDTRANS'
      ? 'Midtrans'
      : provider === 'XENDIT'
        ? 'Xendit'
        : undefined;
  };

  const renderPaymentMethodButton = (method: PaymentChannel) => {
    const imageUrl = getPaymentMethodImageUrl(method);
    const providerLabel = getPaymentMethodProviderLabel(method);
    const displayName = getPaymentMethodDisplayName(method, providerLabel);

    return (
      <button
        key={method.id}
        type="button"
        onClick={() => handlePaymentMethodSelect(method)}
        className={`
          flex w-full flex-col items-center justify-center p-3 rounded-lg border
          text-center transition-all duration-200 ease-in-out
          ${
            selectedPaymentMethod?.id === method.id
              ? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
              : 'border-gray-300 bg-white hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
          }
          focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-opacity-50
          min-h-[80px]
        `}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt={`${displayName} logo`}
            className="w-15 h-10 object-contain mb-4"
          />
        ) : (
          <div className="w-15 h-10 mb-4" />
        )}
        <div className="flex flex-col items-center gap-1">
          <Typography variant="b2" className="text-sm font-medium text-black dark:text-white">
            {displayName}
          </Typography>
        </div>
      </button>
    );
  };



  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    
    // Log debug info

    if (amount === undefined || isNaN(amount)) {
      return;
    }
    if (enforceMinTopup && amount < minTopupAmount) {
      setAmountError(`Minimum topup allowed is ${currencyToSymbol(currency)} ${minTopupAmount.toLocaleString(currencyToLocaleString(currency))}`);
      triggerErrorShake();
      setCurrentView('form');
      requestAnimationFrame(() => {
        amountInputRef.current?.focus();
        amountInputRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
      });
      return;
    }
    if (!selectedPaymentMethod) {
      alert("Please select a payment method.");
      return;
    }
    
    // All payment methods including PayPal go through confirmation modal
    setIsConfirmModalOpen(true);
  };

  const triggerErrorShake = () => {
    if (!isBelowMin) return;
    setShouldShakeError(true);
    if (shakeTimeoutRef.current) {
      clearTimeout(shakeTimeoutRef.current);
    }
    shakeTimeoutRef.current = setTimeout(() => {
      setShouldShakeError(false);
    }, 250);
  };

    const handleCustomAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    const rawValue = value.replace(/\D/g, '');
    const numericValue = Number(rawValue || '0');
    const formattedValue = rawValue
      ? numericValue.toLocaleString(currencyToLocaleString(currency))
      : '';

    setDisplayAmount(formattedValue);
    setAmount(numericValue);
    validateMinTopup(numericValue);
  };

  const handleCustomAmountBlur = () => {
    if (amount !== undefined && !isNaN(amount)) {
      if (amount === 0) {
        setDisplayAmount('');
      } else {
        setDisplayAmount(amount.toLocaleString(currencyToLocaleString(currency)));
      }
    } else {
      setDisplayAmount('');
    }
  };

  const handlePaymentMethodSelect = (method: PaymentChannel) => {
    setSelectedPaymentMethod(method);
    // Don't automatically redirect for PayPal, let user click Top Up first
  };

    const handleAmountClick = (value: number) => {
    setAmount(value);
    setDisplayAmount(value.toLocaleString(currencyToLocaleString(currency)));
    validateMinTopup(value);
  };

    const resetToForm = () => {
    setCurrentView('form');
    setAmount(predefinedAmounts[0]);
    setSelectedPaymentMethod(null);
    setDisplayAmount(predefinedAmounts[0].toLocaleString(currencyToLocaleString(currency)));
    setAmountError(null);
    // Reset payment data
    setVaNumber('');
    setVaBankName('');
    setOtcCode('');
    setMerchantId('');
    setOtcExpiresAt('');
    setQrString('');
    setRedirectUrl('');
    setDeeplinkUrl('');
    setQrCodeUrl('');
    setMobileNumber('');
  };

    const handlePaymentSuccess = (paymentResult: any) => {
    if (!selectedPaymentMethod) return;

    const handledResult = handlePaymentResult(paymentResult, selectedPaymentMethod);

    if (handledResult.success) {
      switch (selectedPaymentMethod.type) {
        case 'VIRTUAL_ACCOUNT':
          if (handledResult.vaNumber) {
            setVaNumber(handledResult.vaNumber);
            setVaBankName(selectedPaymentMethod.name);
            setCurrentView('virtual_account');
          }
          break;
        case 'OTC':
          if (handledResult.otcCode) {
            setOtcCode(handledResult.otcCode);
            setMerchantId(handledResult.merchantId || '');
            setOtcExpiresAt(handledResult.expiresAt || '');
            setCurrentView('otc');
          }
          break;
        case 'QR':
          if (handledResult.qrString) {
            setQrString(handledResult.qrString);
            setCurrentView('qr');
          }
          break;
        case 'EWALLET':
          if (selectedPaymentMethod.code === 'PAYPAL') {
            setPaypalTransactionData(handledResult);
            setCurrentView('paypal');
          } else {
            // Regular E-wallet flow
            setRedirectUrl(handledResult.redirectUrl || '');
            setDeeplinkUrl(handledResult.deeplinkUrl || '');
            setQrCodeUrl(handledResult.qrCodeUrl || '');
            setMobileNumber(handledResult.mobileNumber || '');
            setCurrentView('ewallet');
          }
          break;
        case 'CREDIT_CARD':
          
          // Log payment_session_id if it exists in the details
          if (handledResult.data?.details?.payment_session_id) {
          }
          
          setCreditCardTransactionData(handledResult);
          setCurrentView('credit_card');
          break;
        default:
          alert(handledResult.message || 'Payment initiated successfully!');
          resetToForm();
          break;
      }
    } else {
      alert(handledResult.error || "Top-up failed. Please try again.");
    }
  };


    const handleConfirmTopUp = () => {
    if (formRef.current && amount !== undefined && selectedPaymentMethod) {
      const formData = new FormData(formRef.current);
      formData.set('amount', amount.toString());
      formData.set('paymentMethodId', selectedPaymentMethod.id);
      formData.set('paymentMethodName', selectedPaymentMethod.name);
      formData.set('paymentMethodCode', selectedPaymentMethod.code);
      formData.set('paymentMethodGatewayId', selectedPaymentMethod.gateway_id);
      formData.set('paymentMethodGatewayCode', selectedPaymentMethod.gateway_code || '');
      formData.set('paymentMethodGatewayKey', selectedPaymentMethod.gateway_key || '');
      formData.set('paymentMethodType', selectedPaymentMethod.type);

      startTransition(async () => {
        setIsConfirmModalOpen(false);
        try {
          const result = await createTopUp(formData);

          handlePaymentSuccess(result);
        } catch (error) {
          console.error("Top-up failed:", error);
          alert("Top-up failed. An unexpected error occurred.");
        }
      });
    }
  };

  const handleMidtransCardTokenized = async (paymentTokenId: string) => {
    if (!selectedPaymentMethod) {
      throw new Error('Please select a payment method.');
    }

    const formData = buildMidtransTopupFormData({
      amount,
      paymentMethodId: selectedPaymentMethod.id,
      paymentMethodName: selectedPaymentMethod.name,
      paymentMethodCode: selectedPaymentMethod.code,
      paymentMethodGatewayId: selectedPaymentMethod.gateway_id,
      paymentMethodGatewayCode: selectedPaymentMethod.gateway_code,
      paymentMethodType: selectedPaymentMethod.type,
      paymentTokenId,
    });

    const result = await createTopUp(formData);
    if (!result.success) {
      throw new Error(result.error || 'Failed to initiate credit card payment.');
    }

    if (result.redirectUrl) {
      return { redirectUrl: result.redirectUrl };
    }

    router.push('/wallet');
    return {};
  };

  const handleXenditCardSubmitted = async (cardDetails: XenditCardDetails) => {
    if (!selectedPaymentMethod) {
      throw new Error('Please select a payment method.');
    }

    console.info('[topup][xendit][credit-card] callback', {
      at: new Date().toISOString(),
      amount,
      channelName: selectedPaymentMethod.name,
      gatewayId: selectedPaymentMethod.gateway_id,
      cardNumberLength: cardDetails.cardNumber.replace(/\s/g, '').length,
      hasExpiry: Boolean(cardDetails.expiryMonth && cardDetails.expiryYear),
      hasCvn: Boolean(cardDetails.cvn),
    });

    const formData = buildXenditTopupFormData({
      amount,
      paymentMethodId: selectedPaymentMethod.id,
      paymentMethodName: selectedPaymentMethod.name,
      paymentMethodCode: selectedPaymentMethod.code,
      paymentMethodGatewayId: selectedPaymentMethod.gateway_id,
      paymentMethodGatewayCode: selectedPaymentMethod.gateway_code,
      paymentMethodType: selectedPaymentMethod.type,
      cardNumber: cardDetails.cardNumber,
      expiryMonth: cardDetails.expiryMonth,
      expiryYear: cardDetails.expiryYear,
      cvn: cardDetails.cvn,
      cardholderFirstName: cardDetails.firstName,
      cardholderLastName: cardDetails.lastName,
      cardholderEmail: cardDetails.email,
      cardholderPhoneNumber: cardDetails.phoneNumber,
    });

    const result = await createTopUp(formData);
    console.info('[topup][xendit][credit-card] callback-result', {
      at: new Date().toISOString(),
      success: result.success,
      error: result.error || null,
      hasRedirectUrl: Boolean(result.redirectUrl),
    });
    if (!result.success) {
      throw new Error(result.error || 'Failed to initiate credit card payment.');
    }

    if (result.redirectUrl) {
      return { redirectUrl: result.redirectUrl };
    }

    router.push('/wallet');
    return {};
  };

type ViewState = 'form' | 'virtual_account' | 'otc' | 'qr' | 'ewallet' | 'paypal' | 'credit_card';

  switch (currentView) {
    case 'virtual_account':
      return (
        <VirtualAccountPage
          vaNumber={vaNumber}
          bankName={vaBankName}
          bankLogoUrl={selectedPaymentMethod?.logo_url}
          amount={amount}
          onClose={resetToForm}
        />
      );

    case 'otc':
      return (
        <OTCPage
          otcCode={otcCode}
          merchantId={merchantId}
          expiresAt={otcExpiresAt}
          channelName={selectedPaymentMethod?.name || ''}
          channelLogoUrl={selectedPaymentMethod?.logo_url}
          amount={amount}
          onClose={resetToForm}
        />
      );

    case 'qr':
      return (
        <QRPage
          qrString={qrString}
          channelName={selectedPaymentMethod?.name || ''}
          channelLogoUrl={selectedPaymentMethod?.logo_url}
          amount={amount}
          onClose={resetToForm}
        />
      );

    case 'ewallet':
      return (
        <EWalletPage
          redirectUrl={redirectUrl}
          deeplinkUrl={deeplinkUrl}
          qrCodeUrl={qrCodeUrl}
          channelName={selectedPaymentMethod?.name || ''}
          channelLogoUrl={selectedPaymentMethod?.logo_url}
          amount={amount}
          mobileNumber={mobileNumber}
          onClose={resetToForm}
        />
      );

    case 'paypal':
      return (
        <div className="flex flex-col min-h-screen bg-white dark:bg-gray-900">
          <div className="flex-shrink-0">
            <div className="p-6">
              <button
                onClick={() => setCurrentView('form')}
                className="flex items-center gap-2 text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-white transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
                <span className="font-medium">Back</span>
              </button>
            </div>
          </div>
          
          <div className="flex-1 flex items-center justify-center px-4">
            <div className="w-full max-w-md mx-auto">
              <div className="text-center text-black dark:text-white">
                {/* PayPal Icon */}
                <div className="mx-auto w-24 h-16 md:w-40 md:h-24 bg-white dark:bg-gray-800 rounded-2xl flex items-center justify-center p-4 border border-gray-100 dark:border-gray-700 mb-6">
                  <div className="text-[#0070ba] font-bold text-2xl">PayPal</div>
                </div>

                <h1 className="mb-4 text-3xl font-bold text-brand-500">PayPal Payment</h1>
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
                  Complete your payment securely using PayPal
                </p>

                {/* Payment Details Card */}
                <div className="bg-gray-50 dark:bg-gray-800 rounded-2xl p-6 mb-8">
                  <div className="space-y-6">
                    <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                      <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Payment Method</Typography>
                      <Typography variant="h5" className="font-bold text-black dark:text-white">
                        PayPal
                      </Typography>
                    </div>
                    
                    <div className="flex justify-between items-center py-3">
                      <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount to Pay</Typography>
                      <Typography variant="h5" className="font-bold text-black dark:text-white">
                        {currencyToSymbol(organization?.currency || 'USD')}{amount?.toLocaleString(currencyToLocaleString(organization?.currency || 'USD')) || '0'}
                      </Typography>
                    </div>
                  </div>
                </div>
 
                {/* Instructions */}
                <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl p-4 mb-8 text-left">
                  <div className="flex items-start">
                    <div className="flex-shrink-0 mr-3">
                      <svg className="h-6 w-6 text-blue-400 mt-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                      </svg>
                    </div>
                    <div className="flex-1">
                      <Typography variant="b3" className="text-blue-800 dark:text-blue-200 leading-relaxed">
                        <strong>How to pay:</strong>
                        <br />
                        1. Click the PayPal button below
                        <br />
                        2. You will be redirected to PayPal&apos;s secure payment page
                        <br />
                        3. Log in to your PayPal account or pay as guest
                        <br />
                        4. Complete the payment authorization
                        <br />
                        <br />
                        Your wallet will be credited automatically after successful payment.
                      </Typography>
                    </div>
                  </div>
                </div>

                {/* PayPal Button */}
                <div className="mb-6">
                  <PayPalButton
                    amount={amount || 0}
                    currency="USD" // You might want to map this based on organization country
                    clientId={process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID || 'sb'} // Add this to your env
                    customId={paypalTransactionData?.data?.id || `TOPUP_${Date.now()}`} // Use custom ID from backend
                    onSuccess={() => {
                      // Redirect to wallet page after successful payment
                      router.push('/wallet');
                    }}
                    onError={(error) => {
                      console.error('PayPal payment error:', error);
                      alert('Payment failed. Please try again.');
                    }}
                  />
                </div>

                {/* Cancel Button */}
                <Button 
                  variant="outline" 
                  size="md"
                  onClick={() => setCurrentView('form')}
                  className="w-full text-lg font-semibold border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
                >
                  <Typography variant="s5">Cancel Payment</Typography>
                </Button>
              </div>
            </div>
          </div>
        </div>
      );

    case 'credit_card':

      // Extract payment_session_id from the transaction response
      const paymentSessionId = creditCardTransactionData?.data?.details?.payment_session_id;
      const creditCardProvider =
        creditCardTransactionData?.data?.details?.provider ||
        (selectedPaymentMethod
          ? getCreditCardProvider(
              selectedPaymentMethod.gateway_id,
              selectedPaymentMethod.gateway_code,
            )
          : undefined) ||
        'XENDIT';
      const midtransClientKey = creditCardTransactionData?.data?.details?.client_key;
      
      if (creditCardProvider === 'MIDTRANS') {
        return (
          <CreditCardForm
            paymentSessionId=""
            provider="MIDTRANS"
            clientKey={midtransClientKey}
            amount={amount || 0}
            currency={currency}
            onBack={() => setCurrentView('form')}
            onMidtransTokenized={handleMidtransCardTokenized}
          />
        );
      }

      if (creditCardProvider === 'XENDIT') {
        return <CreditCardForm 
          paymentSessionId={paymentSessionId}
          provider="XENDIT"
          amount={amount || 0}
          currency={currency}
          onBack={() => setCurrentView('form')}
          onXenditCardSubmitted={handleXenditCardSubmitted}
        />;
      }

      if (paymentSessionId) {
        return <CreditCardForm
          paymentSessionId={paymentSessionId}
          provider="XENDIT"
          amount={amount || 0}
          currency={currency}
          onBack={() => setCurrentView('form')}
        />;
      } else {
        // Show payment preview for saved token or redirect
        return (
          <div className="flex flex-col min-h-screen bg-white dark:bg-gray-900">
            <div className="flex-shrink-0">
              <div className="p-6">
                <button
                  onClick={() => setCurrentView('form')}
                  className="flex items-center gap-2 text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-white transition-colors"
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                  </svg>
                  <span className="font-medium">Back</span>
                </button>
              </div>
            </div>
            
            <div className="flex-1 flex items-center justify-center px-4">
              <div className="w-full max-w-md mx-auto">
                <div className="text-center text-black dark:text-white">
                  {/* Credit Card Icon */}
                  <div className="mx-auto w-24 h-16 md:w-40 md:h-24 bg-white dark:bg-gray-800 rounded-2xl flex items-center justify-center p-4 border border-gray-100 dark:border-gray-700 mb-6">
                    <svg className="w-16 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                    </svg>
                  </div>

                  <h1 className="mb-4 text-3xl font-bold text-brand-500">Credit Card Payment</h1>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
                    Complete your payment securely using your credit card
                  </p>

                  {/* Payment Details Card */}
                  <div className="bg-gray-50 dark:bg-gray-800 rounded-2xl p-6 mb-8">
                    <div className="space-y-6">
                      <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                        <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Payment Method</Typography>
                        <Typography variant="h5" className="font-bold text-black dark:text-white">
                          Credit Card
                        </Typography>
                      </div>
                      
                      <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                        <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Transaction ID</Typography>
                        <Typography variant="b3" className="font-mono text-black dark:text-white">
                          {creditCardTransactionData?.data?.id || 'N/A'}
                        </Typography>
                      </div>
                      
                      <div className="flex justify-between items-center py-3">
                        <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount to Pay</Typography>
                        <Typography variant="h5" className="font-bold text-black dark:text-white">
                          {currencyToSymbol(organization?.currency || 'USD')}{amount?.toLocaleString(currencyToLocaleString(organization?.currency || 'USD')) || '0'}
                        </Typography>
                      </div>
                    </div>
                  </div>

                  {/* Redirect Button for Saved Token */}
                  <div className="mb-6">
                    <Button
                      type="button"
                      variant="primary"
                      className="w-full py-4 text-lg"
                      onClick={() => {
                        if (creditCardTransactionData?.data?.redirect_url) {
                          window.location.href = creditCardTransactionData.data.redirect_url;
                        } else {
                          router.push('/wallet');
                        }
                      }}
                    >
                      Proceed to Payment
                    </Button>
                  </div>

                  {/* Cancel Button */}
                  <Button
                    type="button"
                    variant="outline"
                    className="w-full"
                    onClick={() => setCurrentView('form')}
                  >
                    Cancel
                  </Button>
                </div>
              </div>
            </div>
          </div>
        );
      }
      return (
        <div className="flex flex-col min-h-screen bg-white dark:bg-gray-900">
          <div className="flex-shrink-0">
            <div className="p-6">
              <button
                onClick={() => setCurrentView('form')}
                className="flex items-center gap-2 text-gray-600 hover:text-gray-800 dark:text-gray-300 dark:hover:text-white transition-colors"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
                <span className="font-medium">Back</span>
              </button>
            </div>
          </div>
          
          <div className="flex-1 flex items-center justify-center px-4">
            <div className="w-full max-w-md mx-auto">
              <div className="text-center text-black dark:text-white">
                {/* Credit Card Icon */}
                <div className="mx-auto w-24 h-16 md:w-40 md:h-24 bg-white dark:bg-gray-800 rounded-2xl flex items-center justify-center p-4 border border-gray-100 dark:border-gray-700 mb-6">
                  <svg className="w-16 h-12" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                  </svg>
                </div>

                <h1 className="mb-4 text-3xl font-bold text-brand-500">Credit Card Payment</h1>
                <p className="text-sm text-gray-500 dark:text-gray-400 mb-8">
                  Complete your payment securely using your credit card
                </p>

                {/* Payment Details Card */}
                <div className="bg-gray-50 dark:bg-gray-800 rounded-2xl p-6 mb-8">
                  <div className="space-y-6">
                    <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                      <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Payment Method</Typography>
                      <Typography variant="h5" className="font-bold text-black dark:text-white">
                        Credit Card
                      </Typography>
                    </div>
                    
                    <div className="flex justify-between items-center py-3 border-b border-gray-200 dark:border-gray-700">
                      <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Transaction ID</Typography>
                      <Typography variant="b3" className="font-mono text-black dark:text-white">
                        {creditCardTransactionData?.data?.id || 'N/A'}
                      </Typography>
                    </div>
                    
                    <div className="flex justify-between items-center py-3">
                      <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount to Pay</Typography>
                      <Typography variant="h5" className="font-bold text-black dark:text-white">
                        {currencyToSymbol(organization?.currency || 'USD')}{amount?.toLocaleString(currencyToLocaleString(organization?.currency || 'USD')) || '0'}
                      </Typography>
                    </div>
                  </div>
                </div>

                {/* Instructions */}
                <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-xl p-4 mb-8 text-left">
                  <div className="flex items-start">
                    <div className="flex-shrink-0 mr-3">
                      <svg className="h-6 w-6 text-blue-400 mt-1" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                      </svg>
                    </div>
                    <div className="flex-1">
                      <Typography variant="b3" className="text-blue-800 dark:text-blue-200 leading-relaxed">
                        <strong>How to pay:</strong>
                        <br />
                        1. Click &ldquo;Proceed to Payment&rdquo; below
                        <br />
                        2. You will be redirected to a secure payment page
                        <br />
                        3. Enter your credit card details
                        <br />
                        4. Complete the payment process
                        <br />
                        5. You will be redirected back to your wallet
                      </Typography>
                    </div>
                  </div>
                </div>

                {/* Proceed to Payment Button */}
                <div className="mb-6">
                  <Button
                    variant="primary"
                    size="md"
                    onClick={async () => {
                      try {
                        
                        // Hit the /credit-card endpoint with payment_token_id and other data
                        const response = await fetch('/api/topup/credit-card', {
                          method: 'POST',
                          headers: {
                            'Content-Type': 'application/json',
                          },
                          body: JSON.stringify({
                            payment_token_id: creditCardTransactionData?.data?.payment_token_id,
                            amount: amount,
                            gateway_id: creditCardTransactionData?.data?.gateway_id,
                            channel_code: selectedPaymentMethod?.code,
                            transaction_id: creditCardTransactionData?.data?.id,
                          }),
                        });

                        const result = await response.json();

                        if (result.success && result.data?.redirect_url) {
                          // Redirect to credit card payment page
                          window.location.href = result.data.redirect_url;
                        } else {
                          alert('Failed to initiate credit card payment. Please try again.');
                        }
                      } catch (error) {
                        console.error('Credit card payment error:', error);
                        alert('Payment failed. Please try again.');
                      }
                    }}
                    className="w-full text-lg font-semibold py-4"
                  >
                    <Typography variant="s5">Proceed to Payment</Typography>
                  </Button>
                </div>

                {/* Cancel Button */}
                <Button 
                  variant="outline" 
                  size="md"
                  onClick={() => setCurrentView('form')}
                  className="w-full text-lg font-semibold border-2 border-gray-300 text-black dark:border-gray-600 dark:text-white hover:bg-gray-50 dark:hover:bg-gray-800 py-4"
                >
                  <Typography variant="s5">Cancel Payment</Typography>
                </Button>
              </div>
            </div>
          </div>
        </div>
      );

    case 'form':
    default:
      return (
        <ClientOnly>
          <>
            <BackButton />
            <form ref={formRef} onSubmit={handleSubmit}>
              <input type="hidden" name="amount" value={amount !== undefined ? amount : ''} /> 
              <input type="hidden" name="paymentMethodId" value={selectedPaymentMethod?.id || ''} />
              <input type="hidden" name="paymentMethodName" value={selectedPaymentMethod?.name || ''} />
              <input type="hidden" name="paymentMethodGatewayId" value={selectedPaymentMethod?.gateway_id || ''} />

            <div className="mb-6">
              <Typography variant="s1" className="mb-2 font-bold text-black dark:text-white">Step 1: Enter amount</Typography>
              <div className="relative">
                <Typography
                  variant="h3"
                  className={`absolute left-4 top-1/2 -translate-y-1/2 font-normal ${
                    isBelowMin ? 'text-red-600 dark:text-red-400' : 'text-gray-800 dark:text-white/90'
                  }`}
                >
                  {currencyToSymbol(currency)}
                </Typography>
                <input
                  id="customAmount"
                  type="text"
                  ref={amountInputRef}
                  value={displayAmount}
                  onChange={handleCustomAmountChange}
                  onBlur={handleCustomAmountBlur}
                  placeholder="e.g., 65.000"
                  className={`
                    w-full py-2.5 pl-18 max-md:pr-14 focus:outline-hidden focus:ring-0
                    border-b-2
                    ${
                      isBelowMin
                        ? 'border-red-500 focus:border-red-500 text-red-600 placeholder:text-red-300 dark:text-red-400 dark:placeholder:text-red-300'
                        : 'border-gray-300 dark:border-gray-700 text-gray-800 placeholder:text-gray-400 focus:border-brand-500 dark:focus:border-brand-500 dark:text-white/90 dark:placeholder:text-white/30'
                    }
                    dark:bg-white/[0.03]
                    transition-all duration-200 ease-in-out
                    text-2xl lg:text-5xl overflow-auto text-center
                    placeholder:font-normal
                  `}
                />
              </div>
              {amountError && (
                <Typography
                  variant="b2"
                  className={`mt-2 text-sm text-red-600 dark:text-red-400 ${shouldShakeError ? 'animate-shake-once' : ''}`}
                >
                  {amountError}
                </Typography>
              )}
            </div>

            <div className="mb-6">
              <Typography variant="s2" className="mb-2 font-semibold text-black/90 dark:text-white">Quick select</Typography>
              <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-5">
                {predefinedAmounts.map((predefinedAmount) => (
                  <Button
                    key={predefinedAmount}
                    type="button"
                    variant="outline"
                    onClick={() => handleAmountClick(predefinedAmount)}
                    className={`w-full justify-center rounded-lg px-4 py-2 text-center font-medium border
                      bg-transparent text-black border-slate-300 hover:bg-slate-100 
                      dark:text-white dark:border-strokedark dark:hover:bg-slate-800
                      `}
                  >
                    {predefinedAmount.toLocaleString(currencyToLocaleString(currency))}
                  </Button>
                ))}
              </div>
            </div>

            <div className="mt-14">
              <Typography variant="s1" className="mb-1 font-bold text-black dark:text-white">
                Step 2: Select Payment Method
              </Typography>

              {organizedPaymentMethods.every(group => group.methods.length === 0) ? (
                <div className="p-3 text-center">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">
                    This application has not enabled any payment channels yet.
                  </Typography>
                </div>
              ) : (
                organizedPaymentMethods.map(group => {
                  if (shouldRenderCardQrRow && group.title === 'Credit Card' && creditCardGroup && qrGroup) {
                    return (
                      <div key="credit-card-qr-row" className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                        <div>
                          <Typography variant="s2" className="mb-3 font-semibold text-black/90 dark:text-white">
                            Credit Card
                          </Typography>
                          {renderPaymentMethodButton(creditCardGroup.methods[0])}
                        </div>
                        <div>
                          <Typography variant="s2" className="mb-3 font-semibold text-black/90 dark:text-white">
                            QR Payment
                          </Typography>
                          {renderPaymentMethodButton(qrGroup.methods[0])}
                        </div>
                      </div>
                    );
                  }

                  if (shouldRenderCardQrRow && group.title === 'QR Payment') {
                    return null;
                  }

                  const gridClassName = group.methods.length === 1
                    ? 'grid grid-cols-1 gap-3'
                    : 'grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5';

                  return (
                    <div key={group.title} className="mb-6">
                      <Typography variant="s2" className="mb-3 font-semibold text-black/90 dark:text-white">
                        {group.title}
                      </Typography>
                      <div className={gridClassName}>
                        {group.methods.map(renderPaymentMethodButton)}
                      </div>
                    </div>
                  );
                })
              )}
            </div>


            <Button
              type="submit"
              size="md"
              disabled={amount === undefined || !selectedPaymentMethod || isPending}
              onMouseEnter={triggerErrorShake}
              onFocus={triggerErrorShake}
              className="w-full justify-center text-lg font-bold"
            >
              {isPending ? 'Processing...' : 'Top Up'}
            </Button>
          </form>

          {/* Confirmation Modal */}
          <Modal isOpen={isConfirmModalOpen} onClose={() => setIsConfirmModalOpen(false)} className="max-w-md mx-auto p-6 rounded-xl shadow-lg dark:bg-gray-900">
            <div className="text-center text-black dark:text-white">
              <h2 className="mb-2 text-2xl font-bold text-brand-500">Topup Confirmation</h2>
              <p className="text-sm text-gray-500 dark:text-gray-400 mb-6">
                {new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'long', year: 'numeric' })} at {new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false })}
              </p>

              <div className="pt-4 space-y-4 mb-8 text-left">
                <div className="flex justify-between items-center">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Amount:</Typography>
                  <Typography variant="s1" className="font-semibold text-lg text-black dark:text-white">
                    Rp {amount?.toLocaleString(currencyToLocaleString(currency))}
                  </Typography>
                </div>
                <div className="flex justify-between items-center">
                  <Typography variant="b2" className="text-gray-600 dark:text-gray-300">Payment Channel:</Typography>
                  <Typography variant="s1" className="font-semibold text-black dark:text-white">
                    {selectedPaymentMethod
                      ? getPaymentMethodDisplayName(
                          selectedPaymentMethod,
                          getPaymentMethodProviderLabel(selectedPaymentMethod),
                        )
                      : ''}
                  </Typography>
                </div>
              </div>

              <p className="pt-8 text-sm text-yellow-500 dark:text-gray-300 mb-2">
                Please confirm the details above to proceed with your topup*
              </p>

              <div className="flex flex-col gap-3">
                <Button
                  type="button"
                  onClick={handleConfirmTopUp}
                  disabled={isPending}
                >
                  {isPending ? 'Confirming...' : 'Confirm Top Up'}
                </Button>
                <Button
                  type="button"
                  onClick={() => setIsConfirmModalOpen(false)}
                  variant="outline"
                  className="w-full justify-center rounded-md px-6 py-3 border border-slate-300 text-black dark:border-strokedark dark:text-white hover:bg-slate-100 dark:hover:bg-gray-800 text-lg font-semibold"
                >
                  Cancel
                </Button>
              </div>
            </div>
          </Modal>
          </>
        </ClientOnly>
      );
  }
};
