<script setup>
import InputNumber from "@/components/common/InputNumber.vue";
import FileUpload from "@/components/media/FileUpload.vue";
import { omitBy } from "es-toolkit";

const props = defineProps({
  productId: Number,
});

const emit = defineEmits(["created"]);

const { $buildFileUrl, $empty, $insertapi } = useNuxtApp();
const isPending = ref(false);
const body = ref({
  product: props.productId,
  price: null,
  internal_storage: null,
  ram: null,
  color: null,
  image: null,
  note: "",
});

const uploadedImage = ref();

watch(
  () => props.productId,
  (newVal) => {
    body.value.product = newVal;
  },
);

function selected(field, data) {
  if (data === null || field === "price") {
    body.value[field] = data;
  } else {
    body.value[field] = data.id;
  }
}

function onFiles(files) {
  const file = files[0];
  uploadedImage.value = file;
}

async function createProductVariant() {
  isPending.value = true;

  // 1. insert row to Product_Image, get back id
  const productImage = await $insertapi("Product_Image", {
    name: uploadedImage.value.name,
    path: $buildFileUrl(uploadedImage.value.file),
  });
  body.value.image = productImage.id;

  // 2. upload to Product_Variant table
  const trimmedBody = omitBy(body.value, $empty);
  const res = await $insertapi("Product_Variant", trimmedBody);
  isPending.value = false;
  if (res !== "error") {
    emit("created");
  }
}
</script>

<template>
  <div>
    <h1 class="subtitle">Thêm phiên bản</h1>
    <form class="fixed-grid has-12-cols">
      <div class="grid">
        <div class="cell is-col-span-3">
          <div class="field">
            <label class="label">Đơn giá</label>
            <div class="control">
              <InputNumber
                v-bind="{
                  record: body,
                  attr: 'price',
                  placeholder: 'Đơn giá',
                  unit: 'VND',
                }"
                @number="selected('price', $event)"
              />
            </div>
          </div>
        </div>
        <div class="cell is-col-span-3">
          <div class="field">
            <label class="label">Màu sắc</label>
            <SearchBox
              v-bind="{
                api: 'Color',
                field: 'name',
                column: ['name'],
                first: true,
                clearable: true,
                placeholder: 'Màu sắc',
                addon: {
                  component: 'imports/addons/AddColor',
                  width: '60%',
                  height: 'auto',
                  title: 'Thêm màu sắc',
                },
              }"
              @option="selected('color', $event)"
            />
          </div>
        </div>
        <div class="cell is-col-span-3">
          <div class="field">
            <label class="label">RAM</label>
            <SearchBox
              v-bind="{
                api: 'RAM',
                field: 'code',
                column: ['code'],
                first: true,
                clearable: true,
                placeholder: 'RAM',
                addon: {
                  component: 'imports/addons/AddRAM',
                  width: '60%',
                  height: 'auto',
                  title: 'Thêm RAM',
                },
              }"
              @option="selected('ram', $event)"
            />
          </div>
        </div>
        <div class="cell is-col-span-3">
          <div class="field">
            <label class="label">Bộ nhớ trong</label>
            <SearchBox
              v-bind="{
                api: 'Internal_Storage',
                field: 'code',
                column: ['code'],
                first: true,
                clearable: true,
                placeholder: 'Bộ nhớ trong',
                addon: {
                  component: 'imports/addons/AddInternalStorage',
                  width: '60%',
                  height: 'auto',
                  title: 'Thêm bộ nhớ trong',
                },
              }"
              @option="selected('internal_storage', $event)"
            />
          </div>
        </div>
        <div class="cell is-col-span-6">
          <div class="field">
            <label class="label">Ghi chú</label>
            <textarea
              v-model.trim="body.note"
              class="textarea"
              name="note"
              placeholder="Ghi chú"
              rows="5"
            ></textarea>
          </div>
        </div>
        <div class="cell is-col-span-6">
          <div class="field">
            <label class="label">Hình ảnh</label>
            <div class="control is-flex is-gap-1">
              <div>
                <div
                  v-if="uploadedImage"
                  class="relative"
                  style="border: 1px solid var(--bulma-grey-50)"
                >
                  <figure class="image is-128x128">
                    <img :src="$buildFileUrl(uploadedImage.file)" />
                  </figure>
                  <button
                    type="button"
                    class="button is-small is-danger is-light absolute"
                    :style="{ top: '5px', right: '5px' }"
                    @click="uploadedImage = undefined"
                  >
                    <span class="icon">
                      <Icon
                        name="material-symbols:delete-outline-rounded"
                        :size="20"
                      />
                    </span>
                  </button>
                </div>
                <div
                  v-else
                  class="w-36 h-36 rounded-md is-flex is-align-items-center is-justify-content-center"
                  style="border: 1px solid var(--bulma-grey-80)"
                >
                  <Icon
                    name="material-symbols:add-photo-alternate-outline-rounded"
                    :size="40"
                    class="has-text-grey-light"
                  />
                </div>
              </div>
              <FileUpload
                :type="['image']"
                :multiple="false"
                @files="onFiles"
              >
                <template #icon>
                  <Icon
                    name="material-symbols:add-photo-alternate-outline-rounded"
                    :size="20"
                  />
                </template>
                <span class="font-medium">Chọn</span>
              </FileUpload>
            </div>
          </div>
        </div>
        <div class="cell is-col-span-12">
          <button
            :class="['button is-primary', { 'is-loading': isPending }]"
            :disabled="Object.values(body).every($empty)"
            @click.prevent="createProductVariant"
          >
            <span class="icon">
              <Icon
                name="material-symbols:add-rounded"
                :size="18"
              />
            </span>
            <span>Thêm phiên bản</span>
          </button>
        </div>
      </div>
    </form>
  </div>
</template>
