<template>
  <div class="max-w-3xl mx-auto space-y-6 pb-30 safe-top">
    <h2 class="text-2xl text-center">
      Оформление заказа
    </h2>

    <div class="card card-border bg-base-100 w-full">
      <div class="card-body">
        <TgInput
            v-model="checkout.customer.firstName"
            placeholder="Введите имя"
            :error="checkout.validationErrors.firstName"
            :maxlength="32"
            @clearError="checkout.clearError('firstName')"
        />

        <TgInput
            v-model="checkout.customer.lastName"
            placeholder="Введите фамилию"
            :maxlength="32"
            :error="checkout.validationErrors.lastName"
            @clearError="checkout.clearError('lastName')"
        />

        <fieldset class="fieldset">
          <IMaskComponent
              v-model="checkout.customer.phone"
              type="tel"
              class="input input-lg w-full"
              mask="+{7} (000) 000-00-00"
              placeholder="Введите телефон"
              :unmask="true"
          />
          <p v-if="error" class="label text-error">{{ checkout.validationErrors.phone }}</p>
        </fieldset>

        <TgInput
            v-model="checkout.customer.email"
            type="email"
            placeholder="Введите email (опционально)"
            :maxlength="96"
            :error="checkout.validationErrors.email"
            @clearError="checkout.clearError('email')"
        />

        <TgTextarea
            v-model="checkout.customer.comment"
            placeholder="Комментарий (опционально)"
            :error="checkout.validationErrors.comment"
            @clearError="checkout.clearError('comment')"
        />
      </div>
    </div>

    <div
        class="fixed px-4 pb-10 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 v-if="error" class="text-error text-sm">{{ error }}</div>
      <button
          :disabled="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>
  </div>
</template>

<script setup>
import {useCheckoutStore} from "@/stores/CheckoutStore.js";
import TgInput from "@/components/Form/TgInput.vue";
import TgTextarea from "@/components/Form/TgTextarea.vue";
import {useRouter} from "vue-router";
import {computed, ref} from "vue";
import {IMaskComponent} from "vue-imask";

const checkout = useCheckoutStore();
const router = useRouter();
const error = ref(null);

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

async function onCreateBtnClick() {
  try {
    error.value = null;
    await checkout.makeOrder();
    router.push({name: 'order_created'});
  } catch {
    error.value = 'Невозможно создать заказ.';
  }
}
</script>
