<script setup>
import { SelectBox } from 'tedir-select'

const config = useRuntimeConfig()

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

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

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

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([])
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 = []
  const queries = ['value', 'name', 'upc', 'sku', 'm_product_category_id', 'salesrep_id', 'm_attributeset_id', 'issold', 'm_pricelist_version_id'] //, 'm_warehouse_id'
  const defaultUrl = '/api/materials/products/filter'
  let newUrl = defaultUrl
  for(let query of queries) {
    if(form.value[query]) {
      if(newUrl === defaultUrl) {
        if(query === 'value' || query === 'name' || query === 'upc' || query === 'sku') {
          console.log('Hello')
          newUrl += `?${query}=fts.${form.value[query]}`
        }
        else{
        newUrl += `?${query}=eq.${form.value[query]}`
        }
      } else {
        newUrl += `&${query}=eq.${form.value[query]}`
      }
    }
  }
  const res = await $fetch(newUrl)
  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
  }
}

const chooseProduct = async (prod) => {
  let newProd = prod
  if(form.value.priceListVersionId && !prod?.M_ProductPrice?.M_PriceList_Version_ID?.id) {
    const res = await $fetch(`/api/materials/products/price/${prod.id}/${form.value.priceListVersionId}`)
    if(res?.records?.length >= 1) {
      newProd = Object.assign({}, prod, {
        pricestd: res.records[0]?.PriceStd,
        pricelist: res.records[0]?.PriceList,
        pricelimit: res.records[0]?.PriceLimit
      })
    }
  }
  emit('handler', newProd)
  closeProductChooser()
}
</script>

<template>
  <div class="modal" :class="{'active': showProductChooser}" :style="{display: showProductChooser ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeProductChooser">
      <div class="modalContent">
        <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">Product Chooser</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 mnh-450px p-10px">
          <div class="d-flex justify-between flexWrap-wrap p-1.5rem gap-1.5rem">
            <div class="legend w-280px">
              <label class="label">Search Key</label>
              <input type="text" v-model="form.value" class="input" />
            </div>
            <div class="legend w-280px">
              <label class="label">Name</label>
              <input type="text" v-model="form.name" class="input" />
            </div>
            <div class="legend w-280px">
              <label class="label">UPC/EAN</label>
              <input type="text" v-model="form.upc" class="input" />
            </div>
            <div class="legend w-280px">
              <label class="label">SKU</label>
              <input type="text" v-model="form.sku" class="input" />
            </div>
            <div class="legend w-280px">
              <label class="label">Warehouse</label>
              <ClientOnly>
                <SelectBox v-model="form.m_warehouse_id" :options="getWarehouses" @change="(val, opt) => form.warehouse = opt.name" prop="name" dataprop="id" datatype="string" :size="5" />
              </ClientOnly>
            </div>
            <div class="legend w-280px">
              <label class="label">Company Agent</label>
              <ClientOnly>
                <SelectBox v-model="form.salesrep_id" :options="getOptions?.['sales_reps']?.records || [{id: form.salesrep_id, Name: form.salesrep}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'sales_reps')" :loading="loading?.['sales_reps'] ?? true" placeholder="----" />
              </ClientOnly>
            </div>
            <div class="legend w-280px">
              <label class="label">Product Category</label>
              <ClientOnly>
                <SelectBox v-model="form.m_product_category_id" :options="getOptions?.['product_categories']?.records || [{id: form.m_product_category_id, Name: form.product_category}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product_category', 'product_categories')" :loading="loading?.['product_categories'] ?? true" placeholder="----" />
              </ClientOnly>
            </div>
            <div class="legend w-280px">
              <label class="label">Price List Version</label>
              <ClientOnly>
                <SelectBox v-model="form.m_pricelist_version_id" :options="getOptions?.['price_list_versions']?.records || [{id: form.m_pricelist_version_id, Name: form.pricelist_version}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_pricelist_version', 'price_list_versions')" :loading="loading?.['price_list_versions'] ?? true" placeholder="----" />
              </ClientOnly>
            </div>
            <div class="legend w-280px">
              <label class="label">Attribute Set</label>
              <ClientOnly>
                <SelectBox v-model="form.m_attributeset_id" :options="getOptions?.['attribute_sets']?.records || [{id: form.m_attributeset_id, Name: form.attributeset}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_attributeset', 'attribute_sets')" :loading="loading?.['attribute_sets'] ?? true" placeholder="----" />
              </ClientOnly>
            </div>
            <div class="legend w-280px">
              <label class="label">Purchased</label>
              <select v-model="form.issold" class="select">
                <option value="N">No</option>
                <option value="Y">Yes</option>
              </select>
            </div>
            <div>
              <button type="button" class="button" @click="filterProductChooser">Filter</button>
            </div>
          </div>
          <div class="d-flex justify-between 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" @click="chooseProduct(product)">
                <div v-if="product?.gallery?.id" class="productChooserBox">
                  <img v-if="product?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+product?.gallery?.formats?.small?.hash + product?.gallery?.formats?.small?.ext" :alt="product?.gallery?.name" />
                  <img v-else :src="config.public.strapi+'/files-api/'+product?.gallery?.formats?.thumbnail?.hash + product?.gallery?.formats?.thumbnail?.ext" :alt="product?.gallery?.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>
                  <h3>{{ product.Name }}</h3>
                  <h3>Price: {{ product?.M_ProductPrice?.PriceStd || '' }}</h3>
                  <h3>Pricelist: {{ product?.M_ProductPrice?.M_PriceList_Version_ID?.identifier || '' }}</h3>


                </div>
              </div>
            </div>
            <!--<div class="w-300px">
              
            </div>-->
          </div>
        </div>
        <!--<div class="modalFooter">
          <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>