'use client';

import { PayPalButtons, PayPalScriptProvider, ReactPayPalScriptOptions } from '@paypal/react-paypal-js';

interface PayPalButtonProps {
  amount: number;
  currency?: string;
  onSuccess?: (details: any) => void;
  onError?: (error: any) => void;
  clientId: string;
  customId?: string;
}

export function PayPalButton({ 
  amount, 
  currency = 'USD', 
  onSuccess, 
  onError,
  clientId,
  customId 
}: PayPalButtonProps) {  
  // If no client ID provided, show fallback message
  if (!clientId || clientId === 'sb') {
    return (
      <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
        <p className="text-yellow-800 text-sm">
          PayPal is not configured yet. Please set NEXT_PUBLIC_PAYPAL_CLIENT_ID in your environment variables.
        </p>
        <button 
          className="mt-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          onClick={() => {
            // Simulate successful payment for demo
            if (onSuccess) {
              onSuccess({
                id: 'DEMO_PAYMENT_' + Date.now(),
                status: 'COMPLETED',
                payer: {
                  email_address: 'demo@paypal.com'
                }
              });
            }
          }}
        >
          Demo PayPal Payment (Click to simulate success)
        </button>
      </div>
    );
  }

  const initialOptions: ReactPayPalScriptOptions = {
    clientId: clientId,
    currency: currency,
    intent: 'capture',
  };

  return (
    <PayPalScriptProvider options={initialOptions}>
      <PayPalButtons
        style={{
          layout: 'vertical',
          color: 'blue',
          shape: 'rect',
          label: 'paypal',
        }}
        createOrder={(data, actions) => {
          
          const orderData: any = {
            purchase_units: [
              {
                amount: {
                  currency_code: currency,
                  value: amount.toString(),
                },
              },
            ],
            intent: 'CAPTURE',
          };
          
          if (customId) {
            orderData.purchase_units[0].custom_id = customId;
          } else {
            console.error('🔴 PayPal custom_id is missing!');
          }
                    
          return actions.order.create(orderData);
        }}
        onApprove={async (data, actions) => {
          try {
            const details = await actions.order!.capture();
            
            if (onSuccess) {
              onSuccess(details);
            }
          } catch (error) {
            console.error('PayPal capture error:', error);
            if (onError) {
              onError(error);
            }
          }
        }}
        onError={(error) => {
          console.error('PayPal error:', error);
          if (onError) {
            onError(error);
          }
        }}
      />
    </PayPalScriptProvider>
  );
}
