<script setup>
const config = useRuntimeConfig()

const props = defineProps({
  modelValue: Array
})

const emit = defineEmits(['update:modelValue', 'handler'])

const entries = ref(props.modelValue || [])
watch(() => props.modelValue, () => {
  entries.value = props.modelValue
})

const updateCart = () => {
  emit('update:modelValue', entries.value)
}

const destroy = (item, index) => {
  emit('handler', item)
  entries.value.splice(index, 1)
  updateCart()
}
</script>

<template>
  <div class="tableResponsive" @mouseleave="updateCart">
    <table class="table tableList tableFlush">
      <thead>
        <tr> 
          <th colspan="2">Product</th>
          <th>Unit</th>
          <th class="w-120px">Quantity</th>
          <th class="w-120px">Actual</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(entry, index) in entries" :key="index">
          <td class="verticalAlignMiddle">
            <div>
              <div v-if="(entry?.galleries?.length || 0) >= 1" class="productChooserBox" style="width: 40px; height: 40px;">
                <img v-if="entry?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+entry?.galleries[0]?.formats?.small?.hash + entry?.galleries[0]?.formats?.small?.ext" :alt="entry?.galleries[0]?.name" />
                <img v-else :src="config.public.strapi+'/files-api/'+entry?.galleries[0]?.formats?.thumbnail?.hash + entry?.galleries[0]?.formats?.thumbnail?.ext" :alt="entry?.galleries[0]?.name" />
              </div>
              <div v-else class="productChooserBox" style="width: 40px; height: 40px;">
                <img src="https://placehold.co/40x40" alt="Placeholder Image" />
              </div>
            </div>
          </td>
          <td class="verticalAlignMiddle">{{ entry.M_Product_ID.Name }}</td>
          <td class="verticalAlignMiddle">{{ entry.C_UOM_ID.identifier }}</td>
          <td class="verticalAlignMiddle">
            <input type="text" class="input w-60px" v-model="entry.QtyCounter" @input="updateCart" readonly />
          </td>
          <td class="verticalAlignMiddle">{{ entry.QtyEntered }}</td>
          <td class="verticalAlignMiddle textAlignRight">
            <div>
              <!--<span class="cursor-pointer fg-warning">
                <i v-if="entry?.show" class="menu-icon tf-icons ti ti-chevron-up"></i>
                <i v-else class="menu-icon tf-icons ti ti-chevron-down"></i>
              </span>-->
              <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                <i class="menu-icon tf-icons ti ti-trash"></i>
              </span>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>