"use client";

import React, { useState, useEffect, useRef } from "react";
import { PaymentRequestButtonElement, useStripe } from "@stripe/react-stripe-js";

interface StripeWalletFieldsProps {
  amount: number; // in dollars
  label: string;
  onPaymentAuth: (ev: any) => Promise<void>;
}

export default function StripeWalletFields({ amount, label, onPaymentAuth }: StripeWalletFieldsProps) {
  const stripe = useStripe();
  const [paymentRequest, setPaymentRequest] = useState<any>(null);

  // Store the latest callback in a ref to prevent re-initializing the Stripe PaymentRequest
  // every time the parent component re-renders.
  const onPaymentAuthRef = useRef(onPaymentAuth);
  useEffect(() => {
    onPaymentAuthRef.current = onPaymentAuth;
  }, [onPaymentAuth]);

  useEffect(() => {
    if (!stripe) return;

    const pr = stripe.paymentRequest({
      country: "US",
      currency: "usd",
      total: {
        label: label,
        amount: Math.max(1, Math.round(amount * 100)), // convert to cents, ensure greater than 0
      },
      requestPayerName: true,
      requestPayerEmail: true,
    });

    // Check availability
    pr.canMakePayment().then((result) => {
      if (result) {
        setPaymentRequest(pr);
      }
    });

    // Pass the event up to the parent component to handle form submission and payment intent
    pr.on("paymentmethod", async (ev) => {
      if (onPaymentAuthRef.current) {
        await onPaymentAuthRef.current(ev);
      } else {
        ev.complete("fail");
      }
    });

  }, [stripe, amount, label]);

  if (!paymentRequest) return null;

  return (
    <div className="mt-4 animate-in fade-in duration-300">
      <PaymentRequestButtonElement options={{ paymentRequest }} />
      <p className="text-[12px] text-[#828282] mt-2 text-center italic">
        Pay securely using your browser wallet
      </p>
    </div>
  );
}