import { useEffect } from 'react'


const getOptions = ({ name, orderId, razorpayKey, amount, currency, 
    email, contactNumber, address, description,
    //methods
    cancelPayment
}) => ({
    key: razorpayKey, // Enter the Key ID generated from the Dashboard
    amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
    currency,
    name,    
    description,
    order_id: orderId, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1    
    prefill: {
        email,
        contact: contactNumber
    },
    notes: {
        address
    },
    theme: {
        color: "#3399cc"
    },
    // This function is called when the modal is closed by the user.
    modal: { 
        escape: false, 
        ondismiss: function(){ 
        // code here 
            cancelPayment()
            // console.log("closed by user")
        } 
    }
})

//restartPaymentProcess: purpose is to re-invoke the effect if forced to re-initiate
//due to reasons e.g. close of payment box and re-open to do payment
const usePaymentEffect = ({ result, 
    initiatePayment, verifyPayment, cancelPayment = () => {}, paymentFailed }) => {
    
    useEffect( () => {
        if(result != null){
            const {userID, orderDetail } = result
            const startPaymentProcess = async  () => {
                initiatePayment()
                const options = getOptions({...orderDetail, cancelPayment})
                options.handler = (response) => {
                    const {razorpay_payment_id, razorpay_order_id,razorpay_signature} = response
                    // console.log(razorpay_payment_id,razorpay_order_id,razorpay_signature)
                    verifyPayment({
                        userid: userID,
                        razorPaymentId: razorpay_payment_id, 
                        razorOrderId: razorpay_order_id,
                        })
                }
                
                var rzp1 = new window.Razorpay(options)
                rzp1.on('payment.failed', function (response){
                    const {code, description, source, step, reason, metadata} = response.error
                    paymentFailed({
                        code, description, reason
                    })
                    // console.log("payment failed", description, source, step, reason, metadata.payment_id, metadata.order_id)
                })
                rzp1.open()
            }

            startPaymentProcess()
        }

    }, [result])
}
 
export default usePaymentEffect