<template>
  <v-container>

    <v-row>
      <v-text-field label="Message (facultatif)" v-model="tipMessage"
        style="border-radius: 10px; margin-top: 10px; margin-bottom: 10px; color: #a30e79; background-color: #f4f4f4">
      </v-text-field>
    </v-row>

    <v-row>
      <v-text-field label="Montant ($)" v-model="price"
        style="border-radius: 10px; margin-bottom: 10px; color: #a30e79; background-color: #f4f4f4">
      </v-text-field>
    </v-row>

    <v-row justify="center">
      <v-btn @click="goPay()"
        style="margin-bottom: 10px; width: 200px;  background-color: #6b0065; color: white; font-weight: bold;">
        <v-icon left style="margin-right: 10px;">
          mdi-gift
        </v-icon>
        Envoyez
      </v-btn>
    </v-row>

    <v-dialog v-model="isPaymentDialogActive" max-width="720" persistent>
      <template v-slot:default>
        <v-card>
          <div id="checkout">
            <!-- Checkout will insert the payment form here -->
          </div>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn block class="ma-auto" style="width: 200px;" text="Annuler" @click="closeDialog()"></v-btn>
          </v-card-actions>
        </v-card>
      </template>
    </v-dialog>
  </v-container>

</template>

<script setup>
import { useClient } from '@/plugins/api.js';
import { loadStripe } from '@stripe/stripe-js';
import { onMounted, ref } from "vue";

const props = defineProps(['creatorId'])

let stripe = null;
const client = useClient();
const price = ref(0);
const tipMessage = ref("");
const isPaymentDialogActive = ref(false);
var checkout;

onMounted(async () => {
  stripe = await loadStripe(import.meta.env.VITE_STRIPE_API_KEY);
})

const fetchClientSecret = async () => {
  const clientSecret = await createCheckoutSession();
  return clientSecret;
};

async function createCheckoutSession() {
  let clientSecret = await client.post('/api/Stripe', {
    amount: (price.value * 100),
    tipMessage: tipMessage.value,
    creatorId: props.creatorId
  });

  let secret = clientSecret["data"];
  return secret;
}

function closeDialog() {
  isPaymentDialogActive.value = false;
  checkout.destroy();
}

async function goPay() {
  isPaymentDialogActive.value = true;

  checkout = await stripe.initEmbeddedCheckout({
    fetchClientSecret,
  });

  await checkout.mount('#checkout');
}

</script>