import { loadStripe, Stripe } from '@stripe/stripe-js';

// Validate that the publishable key is available
if (!process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) {
  throw new Error('NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY is not defined in environment variables');
}

// Initialize Stripe with publishable key
let stripePromise: Promise<Stripe | null>;

const getStripe = (): Promise<Stripe | null> => {
  if (!stripePromise) {
    stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
  }
  return stripePromise;
};

export default getStripe;

// Export for backward compatibility
export { getStripe as stripePromise };

// Helper function to create payment method
export async function createPaymentMethod(
  stripe: Stripe,
  cardElement: any,
  billingDetails: {
    name: string;
    email: string;
    address?: {
      line1?: string;
      city?: string;
      postal_code?: string;
      country?: string;
    };
  }
) {
  try {
    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: 'card',
      card: cardElement,
      billing_details: billingDetails,
    });

    if (error) {
      throw new Error(error.message);
    }

    return paymentMethod;
  } catch (error) {
    console.error('Error creating payment method:', error);
    throw error;
  }
}

// Helper function to confirm payment
export async function confirmCardPayment(
  stripe: Stripe,
  clientSecret: string,
  paymentMethodId?: string,
  cardElement?: any
) {
  try {
    const confirmOptions: any = {
      payment_method: paymentMethodId,
    };

    if (cardElement && !paymentMethodId) {
      confirmOptions.payment_method = {
        card: cardElement,
      };
    }

    const { error, paymentIntent } = await stripe.confirmCardPayment(
      clientSecret,
      confirmOptions
    );

    if (error) {
      throw new Error(error.message);
    }

    return paymentIntent;
  } catch (error) {
    console.error('Error confirming payment:', error);
    throw error;
  }
}

// Stripe Elements appearance customization
export const stripeElementsOptions = {
  appearance: {
    theme: 'stripe' as const,
    variables: {
      colorPrimary: '#EF7310',
      colorBackground: '#ffffff',
      colorText: '#30313d',
      colorDanger: '#df1b41',
      fontFamily: 'Inter, system-ui, sans-serif',
      spacingUnit: '4px',
      borderRadius: '8px',
    },
    rules: {
      '.Input': {
        border: '1px solid #e6e6e6',
        borderRadius: '8px',
        padding: '12px',
        fontSize: '14px',
      },
      '.Input:focus': {
        border: '1px solid #EF7310',
        boxShadow: '0 0 0 2px rgba(239, 115, 16, 0.1)',
      },
      '.Label': {
        fontSize: '14px',
        fontWeight: '500',
        marginBottom: '8px',
      },
    },
  },
  loader: 'auto' as const,
};

// Country-specific payment methods
export const getPaymentMethodsForCountry = (countryCode: string) => {
  const basePaymentMethods = ['card'];
  
  switch (countryCode.toUpperCase()) {
    case 'CH': // Switzerland
      return [...basePaymentMethods, 'twint'];
    case 'DE': // Germany
      return [...basePaymentMethods, 'sepa_debit', 'sofort'];
    case 'NL': // Netherlands
      return [...basePaymentMethods, 'sepa_debit', 'ideal'];
    case 'BE': // Belgium
      return [...basePaymentMethods, 'sepa_debit', 'bancontact'];
    case 'FR': // France
      return [...basePaymentMethods, 'sepa_debit'];
    case 'IT': // Italy
      return [...basePaymentMethods, 'sepa_debit'];
    case 'ES': // Spain
      return [...basePaymentMethods, 'sepa_debit'];
    case 'PT': // Portugal
      return [...basePaymentMethods, 'sepa_debit'];
    case 'LU': // Luxembourg
      return [...basePaymentMethods, 'sepa_debit'];
    case 'GB': // United Kingdom
      return [...basePaymentMethods, 'bacs_debit'];
    default:
      return basePaymentMethods;
  }
};