﻿<template>
  <button
      class="secondary donation-action"
      @click="openDonationDialog()"
  >
    {{ $t('isupportbtn.isupport') }}
  </button>

  <v-dialog v-model="donationModal">
    <div class="card">
      <div class="card-title">
        {{ $t('isupportbtn.isupport') }}
      </div>

      <div class="card-content">
        <v-text-field
            v-model="tipAmountInDollars"
            type="number"
            autofocus
            placeholder="0"
            :min="0"
            class="p-2"
            :label="`${$t('isupportbtn.amount')}`"
            density="comfortable"
            variant="outlined"
            hide-details
            clearable
            inputmode="numeric"
            @keydown="preventNonNumeric"
            prepend-inner-icon="mdi-currency-usd"
        ></v-text-field>

        <v-textarea
            v-model="tipMessage"
            :label="`${$t('isupportbtn.message')}`"
            class="p-2"
            density="comfortable"
            variant="outlined"
            hide-details
            clearable
        ></v-textarea>
      </div>

      <div class="card-actions">

        <button class="secondary"
                @click="closeDonationDialog()">
          Cancel
        </button>

        <button class="primary"
                @click="goPay()">
          {{ $t('isupportbtn.send') }}
        </button>

      </div>
    </div>
  </v-dialog>

  <v-dialog v-model="isPaymentDialogActive" max-width="720" persistent>
    <template v-slot:default>
      <v-card :style="{ padding: '20px' }">
        <div id="checkout"></div>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

        <v-spacer></v-spacer>

        <v-card-actions>
          <v-btn
              block
              class="ma-auto"
              style="width: 200px"
              @click="closeDialog()"
          >Annuler
          </v-btn>
        </v-card-actions>
      </v-card>
    </template>
  </v-dialog>
</template>

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

const brandingStore = useBrandingStore();

const props = defineProps({
  creatorId: {default: 'missing-creator-id', required: true},
  creatorName: {default: 'missing-creator-name', required: true},
  onSuccessUrl: {default: 'missing-on-success-u', required: true},
  onCancelledUrl: {default: 'missing-on-cancelled-url', required: true},
  iconColorClass: {default: 'text-black'},
});

const errorMessage = ref('');

const donationModal = ref(false);

function openDonationDialog() {
  donationModal.value = true;
}

function closeDonationDialog() {
  donationModal.value = false;
}

const isPaymentDialogActive = ref(false);

const tipAmountInDollars = ref('');
const tipMessage = ref('');

let stripe = null;
let checkout;

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

async function createCheckoutSession() {
  const client = useClient();
  try {
    let clientSecret = await client.post(`/api/tips`, {
      creatorId: props.creatorId,
      amount: tipAmountInDollars.value * 100,
      currency: 'CAD',
      message: tipMessage.value,
      checkoutSuccessUrl: props.onSuccessUrl,
      checkoutCancelledUrl: props.onCancelledUrl,
    });

    return clientSecret.data;
  } catch (error) {
    console.error(error);
    errorMessage.value = 'Une erreur est survenue. Veuillez réessayer.';
  }
}

function closeDialog() {
  isPaymentDialogActive.value = false;
  errorMessage.value = '';

  if (checkout) {
    checkout.destroy();
  }
}

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

  const response = await createCheckoutSession();

  // Redirect to the Stripe Checkout page
  window.location.href = response.stripeCheckoutUrl;
}

function preventNonNumeric(event) {
  const key = event.key;
  const allowedKeys = ['Backspace', 'ArrowLeft', 'ArrowRight', 'Delete'];

  if (!/^\d$/.test(key) && !allowedKeys.includes(key)) {
    event.preventDefault();
  }
}
</script>

<style scoped>

.donation-action {
  @apply bg-hutopyPrimary text-hOnPrimary;
  @apply hover:bg-hutopySecondary;
  @apply w-fit;
}

.error-message {
  color: white;
  background-color: red;
  border-radius: 4px;
  text-align: center;
  width: 100%;
  padding: 5px;
}
</style>
