<script setup>
const props = defineProps({
  variant: Object,
});

const { $empty, $insertapi } = useNuxtApp();
const emit = defineEmits(["created"]);
const isLoading = ref(false);
const body = ref({
  imei: null,
  variant: props.variant.id,
});

async function submit() {
  isLoading.value = true;
  const res = await $insertapi("IMEI", { data: body.value });
  isLoading.value = false;
  if (res !== "error") {
    emit("created");
  }
}
</script>

<template>
  <form class="fixed-grid has-12-cols">
    <div class="grid">
      <div class="cell is-col-span-4">
        <div class="field">
          <label class="label">Variant</label>
          <SearchBox
            v-bind="{
              api: 'Product_Variant',
              field: 'code',
              column: ['code'],
              optionid: variant.id,
              disabled: true,
              first: true,
              placeholder: 'Variant',
            }"
            @option="body.variant = $event?.id ?? $event"
          />
        </div>
      </div>
      <div class="cell is-col-span-6">
        <div class="field">
          <label class="label">IMEI</label>
          <div class="control">
            <input
              v-model.trim="body.imei"
              type="text"
              class="input"
              placeholder="IMEI"
              maxlength="15"
            />
          </div>
          <p class="help is-info">15 chữ số</p>
        </div>
      </div>
      <div class="cell is-col-span-2">
        <div class="field">
          <div class="control">
            <label class="label is-invisible">Submit</label>
            <button
              :class="['button is-primary is-fullwidth', isLoading && 'is-loading']"
              :disabled="$empty(body.imei) || body.imei.length !== 15"
              @click.prevent="submit"
            >
              <span class="icon">
                <Icon
                  name="material-symbols:add-rounded"
                  :size="18"
                />
              </span>
              <span>Thêm</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </form>
</template>
