<script setup>
  import { ref, defineProps, defineEmits, defineExpose, watch } from "vue"
  import ApiService from "@/services/ApiService"
  import { toast } from "vue3-toastify";

  const props = defineProps({
    categoryId: {
      type: String,
      required: true,
    },
    productId: {
      type: Number,
      required: true,
    },
  })

  const emit = defineEmits(["nextStep"])

  const attributes = ref([])

  const selectedAttributes = ref([])

  const rows = ref([])

  const loading = ref(false)

  const loadingAttributes = ref(false)

  const getAttributes = async () => {
    try {
      loading.value = true

      const { data: { data, success } } = await ApiService.get(`admin/attributes`, {
        params: {
          category_id: props.categoryId,
          with_global: 1
      }})

      if (success) {
        attributes.value = data?.filter(attribute => attribute?.translation)
      }
    } catch (e) {
      toast.error(e?.response?.data?.message)
    } finally {
      loading.value = false
    }
  }

  const addRow = () => {
    const newRow = {
      attributes: {},
      price: '',
      stock: '',
    }

    selectedAttributes.value.forEach(attrId => {
      const attr = getAttributeById(attrId)
      if (attr && attr.attribute_values.length > 0) {
        newRow.attributes[attrId] = attr.attribute_values[0].id
      } else {
        newRow.attributes[attrId] = ''
      }
    })
    rows.value.push(newRow)
  }

  const removeRow = async (index) => {
    rows.value.splice(index, 1)
    // if (row.id) {
    //   try {
    //     const { data: { message, success } } = await ApiService.delete(`admin/products/${props.productId}/variants/${row.id}`)
    //
    //     if (success) {
    //       toast.success(message)
    //
    //       rows.value.splice(index, 1)
    //     }
    //   } catch (e) {
    //     toast.error(e?.response?.data?.message);
    //   }
    // } else {
    //
    // }
  }

  const getAttributeById = (id) => {
    return attributes.value.find(attr => attr.id === id)
  }

  watch(selectedAttributes, (newVal) => {
    rows.value.forEach(row => {
      newVal.forEach(attrId => {
        if (!row.attributes[attrId]) {
          const attr = getAttributeById(attrId)
          if (attr && attr.attribute_values.length > 0) {
            row.attributes[attrId] = attr.attribute_values[0].id
          }
        }
      })
      Object.keys(row.attributes).forEach(attrId => {
        if (!newVal.includes(Number(attrId))) {
          delete row.attributes[attrId]
        }

        if (selectedAttributes.value?.length === 0)
          rows.value = []
      })
    })
  })

  const submitAttributes = async () => {
    try {
      loadingAttributes.value = true

      await ApiService.post(`admin/products/${props.productId}/attributes`, {
        attributes: selectedAttributes.value,
      })

      const { data: { success, message } } = await ApiService.post(`admin/products/${props.productId}/variants`, {
        productVariants: rows.value?.map(variant => ({
          price: variant?.price,
          inventory: variant?.stock,
          attributeValues: Object.values(variant?.attributes)
        })),
      })

      if (success) {
        toast.success(message)
        emit('nextStep')
      }
    } catch (e) {
      toast.error(e.response?.data?.message)
    } finally {
      loadingAttributes.value = false
    }
  }

  const handlerChangeCheckbox = async () => {
    // if (!e.target.checked) {
    //   try {
    //     const { data: { success, message } } = await ApiService.delete(`admin/products/${props.productId}/attributes/${attr.id}`)
    //
    //     if (success) {
    //       toast.success(message)
    //     }
    //   } catch (e) {
    //     toast.error(e.response?.data?.message)
    //   }
    // }
  }

  getAttributes()

  defineExpose({ attributes, rows, selectedAttributes })
</script>

<template>
   <span v-if="loading" class="d-flex justify-content-center w-100">
     <i class="fa fa-spinner fa-spin text-2xl"></i>
   </span>

  <div v-else class="pt-8">
    <div>
      <div v-for="attr in attributes" :key="attr.id" class="mb-2 form-check">
        <input
            type="checkbox"
            :id="'attr-' + attr?.id"
            :value="attr?.id"
            v-model="selectedAttributes"
            @change="handlerChangeCheckbox($event, attr)"
            class="form-check-input"
        />
        <label :for="'attr-' + attr.id" class="form-check-label">{{ attr?.translation?.title }}</label>
      </div>

      <template v-if="selectedAttributes?.length">
        <div v-for="(row, i) in rows" :key="row.id" class="border p-3 rounded mt-4 d-flex items-center gap-3">
          <div v-for="attrId in selectedAttributes" :key="attrId">
            <select
                v-model="row.attributes[attrId]"
                :id="'attr-' + attrId"
                class="border rounded px-2 py-1 form-select"
                :style="{ minWidth: '200px' }"
            >
              <option
                  v-for="val in getAttributeById(attrId)?.attribute_values?.filter(attribute => attribute?.translation)"
                  :key="val.id"
                  :value="val.id"
              >
                {{ val.translation?.title }}
              </option>
            </select>
          </div>

          <!-- Extra fields -->
          <input
              v-model="row.price"
              type="text"
              placeholder="قیمت"
              class="border rounded px-2 py-1 w-24"
          />
          <input
              v-model="row.stock"
              type="text"
              placeholder="تعداد موجود"
              class="border rounded px-2 py-1 w-24"
          />

          <!-- Delete button -->
          <button
              @click="removeRow(i)"
              class="btn btn-danger btn-outline rounded btn-sm"
          >
            <i class="ti ti-trash me-1 text-xl"></i>
          </button>
        </div>

        <button
            v-if="selectedAttributes?.length"
            @click="addRow"
            class="mt-4 btn btn-primary text-white px-3 py-2 rounded w-100"
        >
          <i class="ti ti-plus"></i>
          افزودن سطر جدید
        </button>

        <hr class="my-4" />

        <div class="d-flex justify-content-between align-items-center">
          <button
              v-if="selectedAttributes?.length"
              :disabled="loadingAttributes"
              @click="submitAttributes"
              class="mt-4 btn btn-primary text-white px-3 py-2 rounded"
          >
            <span v-if="loadingAttributes">
              <i class="fa fa-spinner fa-spin"></i> بارگذاری...
            </span>
            <template v-else>
              ذخیره ویژگی ها
            </template>
          </button>

          <div>
            <slot />
          </div>
        </div>

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

<style scoped>

</style>