<template>
  <BaseViewWrapper title="Оформление заказа" class="pb-10">
    <div
        v-if="isLoading"
        class="flex items-center justify-center h-20">
      <span class="loading loading-spinner loading-xl"></span>
    </div>

    <div v-else-if="checkoutFormSchema" class="w-full">
      <FormKit
          type="form"
          id="form-checkout"
          ref="checkoutFormRef"
          v-model="checkout.form"
          :actions="false"
          @submit="onFormSubmit"
      >
        <FormKitSchema :schema="checkoutFormSchema" :data="data"/>
      </FormKit>
    </div>

    <div v-else>
      <div role="alert" class="alert alert-warning alert-outline">
        <IconWarning/>
        <span>
            Форма заказа не сконфигурирована. <br>
            Пожалуйста, укажите параметры формы в настройках модуля, чтобы эта секция работала корректно.
          </span>
      </div>
    </div>

    <div
        class="fixed bottom-fix px-4 pb-4 pt-4 bottom-0 left-0 w-full bg-base-200 z-50 flex flex-col justify-between items-center gap-2 border-t-1 border-t-base-300">

      <div class="text-error">{{ checkout.errorMessage }}</div>
      <div>
        <FormKitMessages :node="checkoutFormRef?.node"/>
      </div>
      <button
          :disabled="isLoading || ! checkoutFormSchema || checkout.isLoading"
          class="btn btn-primary w-full"
          @click="onCreateBtnClick"
      >
        <span v-if="checkout.isLoading" class="loading loading-spinner loading-sm"></span>
        {{ btnText }}
      </button>

    </div>
  </BaseViewWrapper>
</template>

<script setup>
import {useCheckoutStore} from "@/stores/CheckoutStore.js";
import {useRoute, useRouter} from "vue-router";
import {computed, onMounted, ref} from "vue";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";
import {YA_METRIKA_GOAL} from "@/constants/yaMetrikaGoals.js";
import {FormKit, FormKitMessages, FormKitSchema} from '@formkit/vue';
import {submitForm} from '@formkit/core';
import IconWarning from "@/components/Icons/IconWarning.vue";
import {useFormsStore} from "@/stores/FormsStore.js";
import BaseViewWrapper from "@/views/BaseViewWrapper.vue";

const checkout = useCheckoutStore();
const yaMetrika = useYaMetrikaStore();
const forms = useFormsStore();
const route = useRoute();
const router = useRouter();
const error = ref(null);

const isLoading = ref(false);
const checkoutFormSchema = ref(null);
const checkoutFormRef = ref(null);

const btnText = computed(() => {
  return checkout.isLoading ? 'Подождите...' : 'Создать заказ';
});

import { reactive } from 'vue';
const data = reactive(checkout.form);

function onCreateBtnClick() {
  try {
    submitForm('form-checkout');
  } catch (error) {
    console.error(error);
    error.value = 'Невозможно создать заказ.';
  }
}

async function onFormSubmit() {
  console.log('[Checkout]: submit form');

  try {
    error.value = null;
    yaMetrika.reachGoal(YA_METRIKA_GOAL.CREATE_ORDER, {
      price: checkout.order?.final_total_numeric,
      currency: checkout.order?.currency,
    });

    await checkout.makeOrder();

    router.push({name: 'order_created'});
  } catch (error) {
    console.error(error);
    error.value = 'Невозможно создать заказ.';
  }
}

async function loadCheckoutFormSchema() {
  try {
    isLoading.value = true;
    const response = await forms.getFormByAlias('checkout');
    if (response?.data?.schema && response.data.schema.length > 0) {
      checkoutFormSchema.value = response.data.schema;
    }
  } catch (error) {
    console.error('Failed to load checkout form: ', error);
    checkoutFormSchema.value = false;
  } finally {
    isLoading.value = false;
  }
}

onMounted(async () => {
  window.document.title = 'Оформление заказа';

  await loadCheckoutFormSchema();

  yaMetrika.pushHit(route.path, {
    title: 'Оформление заказа',
  });
  yaMetrika.reachGoal(YA_METRIKA_GOAL.VIEW_CHECKOUT);
});
</script>
