import { Controller } from '@hotwired/stimulus';
import { MvMessage } from '../scripts/mvMessage';


/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="hello" attribute will cause
 * this controller to be executed. The name "hello" comes from the filename:
 * hello_controller.js -> "hello"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {

    connect() {
        const stripe = Stripe('pk_live_51LI64DLzRBS4wLfnGrXQu4iNaTZ3iSrsV5sVhwnEwcfnbSQ1fNiCtFbwLHLxDUvx9tq6IPmZdevwNmEMZrQ9xlR6003IRdFtdF');
        // const stripe = Stripe('pk_live_51LI64DLzRBS4wLfnGrXQu4iNaTZ3iSrsV5sVhwnEwcfnbSQ1fNiCtFbwLHLxDUvx9tq6IPmZdevwNmEMZrQ9xlR6003IRdFtdF');

        // let message = new MvMessage();
        // $('#email').on('keyup',(e)=>{
        //     if(e.target.value!==''){
        //         $('#payCharge').attr('disabled',false)
        //     }else{
        //         $('#payCharge').attr('disabled',true)
        //     }
        // })
        $("#payCharge").on('click',(e)=>{
            initIntent();
                   })
        function initIntent() {
            let clientsecret = '';
            console.log('Ok');
            $.ajax({
                method: "GET",
                url: '/stripe/new' ,
                data: {}
            })
                .done(function( response ) {
                    clientsecret = response.client_secret
                    console.log('initSuccess')
                    initForm(clientsecret)

                })
                .fail()
                .always();
        }
        function initForm(clientsecret){

            const options = {
                clientSecret: clientsecret,
                // Fully customizable with appearance API.
                appearance: {/*...*/},
            };

// Set up Stripe.js and Elements to use in checkout form, passing the client secret obtained in step 3
            const elements = stripe.elements(options);

// Create and mount the Payment Element
            const paymentElement = elements.create('payment');
            paymentElement.mount('#payment-element');

            // Confirmation paiment
            const form = document.getElementById('payment-form');
            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                const {error} = await stripe.confirmPayment({
                    //`Elements` instance that was used to create the Payment Element
                    elements,
                    confirmParams: {
                        return_url: window.location.href+'/'+$('#email').val(),
                    },
                });

                if (error) {
                    // This point will only be reached if there is an immediate error when
                    // confirming the payment. Show error to your customer (for example, payment
                    // details incomplete)
                    const messageContainer = document.querySelector('#error-message');
                    messageContainer.textContent = error.message;
                } else {
                    // Your customer will be redirected to your `return_url`. For some payment
                    // methods like iDEAL, your customer will be redirected to an intermediate
                    // site first to authorize the payment, then redirected to the `return_url`.
                }
            });
        }


        // Status
// Retrieve the "payment_intent_client_secret" query parameter appended to
// your return_url by Stripe.js

// Retrieve the PaymentIntent
        function status() {

            stripe.retrievePaymentIntent(clientsecret).then(({paymentIntent}) => {
                const message = document.querySelector('#message')

                // Inspect the PaymentIntent `status` to indicate the status of the payment
                // to your customer.
                //
                // Some payment methods will [immediately succeed or fail][0] upon
                // confirmation, while others will first enter a `processing` state.
                //
                // [0]: https://stripe.com/docs/payments/payment-methods#payment-notification
                switch (paymentIntent.status) {
                    case 'succeeded':
                        message.innerText = 'Success! Payment received.';
                        break;

                    case 'processing':
                        message.innerText = "Payment processing. We'll update you when payment is received.";
                        break;

                    case 'requires_payment_method':
                        message.innerText = 'Payment failed. Please try another payment method.';
                        // Redirect your user back to your payment page to attempt collecting
                        // payment again
                        break;

                    default:
                        message.innerText = 'Something went wrong.';
                        break;
                }
            });
        }
    }
}

