/** @format */

import React, { useRef } from "react";
import { View, ActivityIndicator } from "react-native";
import { WebView } from "react-native-webview";
import { AmazonPayParams } from "@/types/payment";

type AmazonProps = {
  config: AmazonPayParams | null;
};

const Amazon: React.FC<AmazonProps> = ({ config }) => {
  const webviewRef = useRef<WebView>(null);

  if (!config) return null;

  const configJSON = JSON.stringify({
    merchantId: config.merchantId,
    publicKey: config.publicKey,
    amount: config.amount,
    currency: config.currency,
    payload: config.payload,
    signature: config.signature,
  });

  const htmlContent = `
    <!DOCTYPE html>
    <html>
      <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://static-na.payments-amazon.com/checkout.js"></script>
      </head>
      <body>
        <div id="AmazonPayButton"></div>
        <script>
          document.addEventListener('DOMContentLoaded', function() {
            var cfg = ${configJSON};
            if (window.amazon && window.amazon.Pay) {
              var button = window.amazon.Pay.renderButton('#AmazonPayButton', {
                merchantId: cfg.merchantId,
                publicKeyId: cfg.publicKey,
                ledgerCurrency: 'USD',
                checkoutLanguage: 'en_US',
                productType: 'PayOnly',
                placement: 'Other',
                buttonColor: 'Gold',
              });

              button.onClick(function() {
                button.initCheckout({
                  estimatedOrderAmount: {
                    amount: String(cfg.amount),
                    currencyCode: cfg.currency,
                  },
                  createCheckoutSessionConfig: {
                    payloadJSON: cfg.payload,
                    signature: cfg.signature,
                    algorithm: 'AMZN-PAY-RSASSA-PSS-V2',
                    publicKeyId: cfg.publicKey,
                  },
                });
              });
            }
          });
        </script>
      </body>
    </html>
  `;

  return (
    <View style={{ flex: 1 }}>
      <WebView
        ref={webviewRef}
        originWhitelist={["*"]}
        source={{ html: htmlContent }}
        startInLoadingState
        renderLoading={() => (
          <ActivityIndicator size="large" style={{ flex: 1 }} />
        )}
      />
    </View>
  );
};

export default Amazon;
