<script setup>
import { string } from 'alga-js'
import { toast } from 'bulma-toast'
import { SelectBox } from 'tedir-select'

const config = useRuntimeConfig()

const props = defineProps({
  modelValue: Boolean,
  info: Object,
  lines: Array
})

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

const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')

const scanInput = ref('')
const scanAudio = ref(null)
const scanProcessing = ref(false)
const form = ref({
  value: '',
  name: '',
  upc: '',
  sku: '',
  warehouse: props.info?.warehouse || warehouse.value?.Name || '',
  m_warehouse_id: props.info?.warehouseId || warehouseId.value || '',
  product_category: '',
  m_product_category_id: '',
  price_list_version: '',
  m_pricelist_version_id: '',
  attributeset: '',
  m_attributeset_id: '',
  salesrep: '', //props.info?.salesRep || '',
  salesrep_id: '', //props.info?.salesRepId || '',
  issold: 'Y'
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res

    if(getOptions.value[key]?.records) {
      getOptions.value[key].records.unshift({
        id: '',
        Name: '-- Select Option --',
        ISO_Code: '-- Select Option --',
        Address1: '-- Select Option --'
      })
    }
  }
  loading.value[key] = false
}

const getPriceListVersion = async () => {
  if(props.info?.priceListId) {
    const res = await $fetch(`/api/materials/products/price/version/${props.info.priceListId}`)
    if(res?.records?.length >= 1) {
      form.value.m_pricelist_version_id = res.records[0].id
      form.value.price_list_version = res.records[0].Name

      await setOptions('models/m_pricelist_version', 'price_list_versions')
    }
  }
}
onMounted(getPriceListVersion)
watch(() => props.info, () => {
  form.value.warehouse = props.info.warehouse || warehouse.value?.Name || ''
  form.value.m_warehouse_id = props.info.warehouseId || warehouseId.value || ''
  // form.value.salesrep = props.info.salesRep
  // form.value.salesrep_id = props.info.salesRepId

  getPriceListVersion()
})

const getWarehouses = computed(() => {
  const newWarehoues = unref(warehouses)
  if(Number(newWarehoues.filter(i => i.id === '').length) === 0) {
    newWarehoues.unshift({
      id: '',
      name: '-- Select Option --'
    })
  }
  return newWarehoues
})

const showProductChooser = ref(props.modelValue || false)
const closeProductChooser = () => {
  showProductChooser.value = false
  emit('update:modelValue', showProductChooser.value)
}
watch(() => props.modelValue, () => {
  showProductChooser.value = props.modelValue
  getPriceListVersion()
})

const products = ref([])
watch(() => props.modelValue, () => {
  scanInput.value = ''
  products.value = []
  scanProcessing.value = false
})

const filterProductGallery = (galleries, strapiProduct) => {
  let newGallery = galleries?.[0] ?? {}
  if(strapiProduct?.Main_Image && strapiProduct?.Main_Image != 0) {
    newGallery = galleries.filter(i => i.id == strapiProduct.Main_Image)?.[0] ?? {}
  }
  return newGallery
}
const filterProductChooser = async () => {
  products.value = []
  let newScan = string.urlEncode(`
    contains(Value,'${scanInput.value}') 
    OR contains(Name,'${scanInput.value}') 
    OR contains(UPC,'${scanInput.value}')
    OR contains(SKU,'${scanInput.value}')
  `)
  const res = await $fetch(`/api/materials/products/scan?q=${newScan}`)
  if(res) {
    products.value = res?.records || []
    const newProducts = []
    for(let item of res?.records || []) {
      if(item?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${item.Strapi_Product_documentId}/galleries`)
        if(resp?.data) {
          item.galleries = resp.data?.image ?? []
          item.gallery = filterProductGallery(item.galleries, resp.data)
        }
      }
      newProducts.push(item)
    }
    products.value = newProducts

    if(products.value.length == 1) {
      chooseProduct(products.value[0])
    }
  }
}

onMounted(() => {
  if(scanAudio.value === null) {
    scanAudio.value = new Audio('/mp3/store-scanner-beep-90395.mp3')
  }
})

const chooseProduct = (prod) => {
  scanProcessing.value = true
  //const existingLine = props.lines?.filter(i => i.productId == prod.id)?.[0] ?? null
  //if(!existingLine) {
    if(scanAudio.value === null) {
      scanAudio.value = new Audio('/mp3/store-scanner-beep-90395.mp3')
    }
    scanAudio.value.play()
    scanAudio.value.onended = (event) => {
      emit('handler', prod)
      scanProcessing.value = false
      scanInput.value = ''
      products.value = []
      toast({
        message: `Product ${prod.Name} has been added`,
        type: 'is-success',
        duration: 2000
      })
    }
  /*} else {
    emit('handler', prod)
    scanProcessing.value = false
  }*/
  //closeProductChooser()
}

const lineProduct = (id) => {
  return props.lines?.filter(i => i.productId == id)?.[0] ?? {}
}
</script>

<template>
  <div class="modal" :class="{'active': showProductChooser}" :style="{display: showProductChooser ? 'block' : 'none'}">
    <div class="modalDialog modalCenter" @click.self="closeProductChooser">
      <div class="modalContent d-flex flexDirection-column">
        <div class="modalHeader modalHeaderNoPad">
          <div class="flexGrow-1">
            <div class="d-flex justify-between bb-1px_solid_hexe2e2e2 p-0.75rem gap-0.75rem">
              <h3 class="modalTitle">Scan Product</h3>
              <div class="cursor-pointer" @click="closeProductChooser">
                <span class="tf-icon ti ti-x ti-sm me-1"></span>
              </div>
            </div>
          </div>
        </div>
        <div class="modalBody flexGrow-1">
          <div class="columns is-desktop h-100pct">
            <div class="column is-full">
              <div>
                <div>
                  <div class="d-flex justify-between p-0.75rem gap-10px">
                    <div class="flexGrow-1">
                      <input type="text" v-model="scanInput" class="input" @keyup.enter="filterProductChooser" />
                    </div>
                    <div>
                      <button type="button" class="button" @click="filterProductChooser">Filter</button>
                    </div>
                  </div>
                </div>
              </div>
              <div class="d-flex justify-between p-0.75rem gap-10px">
                <div class="d-flex flexGrow-1 flexWrap-wrap gap-0.75rem">
                  <div v-for="(product, index) in products" :key="index" class="card w-145px mb-0px" :class="scanProcessing ? 'pointerEvents-none opacity-0.6' : ''" @click="chooseProduct(product)">
                    <div v-if="(product?.galleries?.length || 0) >= 1" class="productChooserBox">
                      <img v-if="product?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+product?.galleries[0]?.formats?.small?.hash + product?.galleries[0]?.formats?.small?.ext" :alt="product?.galleries[0]?.name" />
                      <img v-else :src="config.public.strapi+'/files-api/'+product?.galleries[0]?.formats?.thumbnail?.hash + product?.galleries[0]?.formats?.thumbnail?.ext" :alt="product?.galleries[0]?.name" />
                    </div>
                    <div v-else class="productChooserBox">
                      <img src="https://placehold.co/145x128" alt="Placeholder Image" />
                    </div>
                    <div class="cardBody p-10px preventSelectText">
                      <h3>{{ product.Value }}</h3>
                      <h4 class="opacity-0.6">{{ product.Name }}</h4>
                      <div class="d-flex justify-between gap-10px">
                        <div></div>
                        <div class="textAlign-right">{{ lineProduct(product.id)?.qtyEntered ?? 0 }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
        </div>
        <!--<div class="modalFooter" style="padding: 1.5rem !important;">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closeProductChooser">Close</button>
            <button type="button" class="button" :class="(products.length == 0) ? 'pointerEvents-none opacity-0.6' : ''">Select</button>
          </div>
        </div>-->
      </div>
    </div>
  </div>
</template>

<style scoped>
.preventSelectText {
  -webkit-user-select: none; /* Safari */
  -ms-user-select: none; /* IE 10 and IE 11 */
  user-select: none; /* Standard syntax */
  pointer-events: none;
  cursor: default;
}
</style>