<template>
  <div class="max-w-3xl mx-auto p-4 space-y-6 pb-30">
    <h2 class="text-2xl">
      Оформление заказа
    </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"
            @clearError="checkout.clearError('firstName')"
        />

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

        <TgInput
            v-model="checkout.customer.email"
            type="email"
            placeholder="Введите email"
            :error="checkout.validationErrors.email"
            @clearError="checkout.clearError('email')"
        />

        <TgInput
            v-model="checkout.customer.phone"
            type="tel"
            placeholder="Введите телефон"
            :error="checkout.validationErrors.phone"
            @clearError="checkout.clearError('phone')"
        />

        <TgInput
            v-model="checkout.customer.address"
            placeholder="Адрес доставки"
            :error="checkout.validationErrors.address"
            @clearError="checkout.clearError('address')"
        />

        <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 class="btn btn-primary w-full" @click="onCreateBtnClick">Создать заказ</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 {ref} from "vue";

const checkout = useCheckoutStore();
const router = useRouter();

const error = ref(null);

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