import React from 'react';
import { loadStripe } from '@stripe/stripe-js';
import { Elements, useStripe, useElements, CardElement } from '@stripe/react-stripe-js';
import {MyProductData, StripeSubscriptionCreate} from '../../services/services';
import {useQuery} from "@tanstack/react-query";
import queryKeys from "../../services/queryKeys";
import { useNavigate } from 'react-router-dom';
//const stripePromise = loadStripe('your_stripe_publishable_key');
const stripePromise = loadStripe('pk_test_51RqL5WLjZLojw6IZmEpwFidNZSl9lLlVUHNvuFZNEz1eTR9XXepnyyVhfvXe9cp4eMnqkDPpoe9wxLLRSV0dxRee00UfhayUOT');

const CheckoutForm = ({ priceId, customerId ,option_name }) => {
    const stripe = useStripe();
    const elements = useElements();
    const navigate = useNavigate();
    const handleSubmit = async (event) => {
        event.preventDefault();

        if (!stripe || !elements) {
            return;
        }

        let reqData = {
            priceId : priceId,
            customerId: customerId,
            option_name: option_name,
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid') // USER UID
        }

        StripeSubscriptionCreate(reqData).then( (res)=>{
            console.log(res);
            console.log(res.data.stripe_session);
            //navigate(res.data.stripe_session)
            window.location.replace(res.data.stripe_session);
        });

    };

    return (
        <form onSubmit={handleSubmit}>
            <CardElement />
            <button type="submit" disabled={!stripe}>
                Subscribe
            </button>
        </form>
    );
};

const StripeSubscriptionButton = ({ priceId, customerId ,option_name}) => {
    return (
        <Elements stripe={stripePromise}>
            <CheckoutForm priceId={priceId} customerId={customerId} option_name={option_name} />
        </Elements>
    );
};

export default StripeSubscriptionButton;