<script setup>
import { date, array, string } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { toast } from 'bulma-toast'

const route = useRoute()
const config = useRuntimeConfig()
const organizationId = useCookie('logship_organization_id')
const warehouseId = useCookie('logship_warehouse_id')

const props = defineProps({
  modelValue: Array,
  action: String,
  info: Object
})

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

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

const lineNumber = computed(() => {
  let lineNum = 1
  if(Number(entries.value.length || 0) === 1) {
    lineNum = 2
  } else if(Number(entries.value.length || 0) >= 2) {
    lineNum = Number(array.math(entries.value, 'max', 'line')) + 1
  }
  return lineNum
})

const addLine = () => {
  entries.value.push({
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    rma: props.info?.documentNo || '',
    rmaId: props.info?.id || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qty: 1,
    amt: 0,
    lineNetAmt: 0,
    processed: false,
    tax: '',
    taxId: '',
    inOutLine: '',
    inOutLineId: '',
    charge: '',
    chargeId: '',
    show: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  })
}

const loading = ref({})
const filtering = ref({})
const products = ref({})
const getOptions = 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 setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res

    if(key.startsWith('products_') && Number(res?.records?.length) >= 1) {
      products.value[key] = 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[key] = newProducts
    }
  }
  loading.value[key] = false
}

const filterOptions = async (model, key, filter = '') => {
  if(filter) {
    await setOptions('filters/'+model+'/'+filter, key)
    filtering.value[key] = filter
  } else {
    if(!filtering.value?.[key] || filtering.value?.[key] === '') {
      await setOptions('models/'+model, key)
    }
  }
}

const filterProducts = async (url, key, filter = '') => {
  const newWarehouseId = props.info?.warehouseId || warehouseId.value

  if(props.info?.priceListId) {
    const res = await $fetch(`/api/materials/products/price/version/${props.info.priceListId}`)
    if(res?.records?.length >= 1) {
      const newPriceListVersionId = res.records[0].id

      if(filter) {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&m_pricelist_version_id=eq.${newPriceListVersionId}&name=fts.${filter}`, key)
        filtering.value[key] = filter
      } else {
        if(!filtering.value?.[key] || filtering.value?.[key] === '') {
          await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&m_pricelist_version_id=eq.${newPriceListVersionId}`, key)
        }
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&name=fts.${filter}`, key)
      filtering.value[key] = filter
    } else {
      if(!filtering.value?.[key] || filtering.value?.[key] === '') {
        await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}`, key)
      }
    }
  }
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/invoices/'+route.params.id+'/invoice-line', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          rma: item?.M_RMA_ID?.identifier || '',
          rmaId: item?.M_RMA_ID?.id || '',
          isActive: item?.IsActive ?? true,
          line: item?.Line || '',
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          galleries: [],
          qty: item?.Qty || 1,
          amt: item?.Amt || 0,
          lineNetAmt: item?.LineNetAmt || 0,
          processed: item?.Processed ?? false,
          tax: item?.C_Tax_ID?.identifier || '',
          taxId: item?.C_Tax_ID?.id || '',
          inOutLine: item?.M_InOutLine_ID?.identifier || '',
          inOutLineId: item?.M_InOutLine_ID?.id || '',
          charge: item?.C_Charge_ID?.identifier || '',
          chargeId: item?.C_Charge_ID?.id || '',
          show: false,
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      }).sort((a, b) => Number(a.line) - Number(b.line))
      
      const newEntries = []
      for(let item of entries.value) {
        const response = await $fetch(`/api/materials/products/${item.productId}`)
        if(response?.Strapi_Product_documentId) {
          const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries`)
          if(resp?.data) {
            item.galleries = resp.data?.image ?? []
            item.gallery = filterProductGallery(item.galleries, resp.data)
          }
        }
        newEntries.push(item)
      }
      entries.value = newEntries
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  entries.value.splice(index, 1)

  if(entry.id) {
    await $fetch('/api/invoices/'+entry.id+'/invoice-line', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const chooseLineIndex = ref(NaN)
const chooseLineEntry = ref(null)
const showProductChooser = ref(false)
const hideProductCharge = ref(false)
const productChooserHandler = (prod) => {
  if(chooseLineIndex.value !== NaN && chooseLineEntry.value !== null) {
    const newEntry = chooseLineEntry.value
    newEntry.product = prod?.Name || ''
    newEntry.productId = prod?.id || ''
    newEntry.amt = prod?.M_ProductPrice?.PriceList || prod?.M_ProductPrice?.PriceStd || 0
    newEntry.charge = ''
    newEntry.chargeId = ''
    newEntry.lineNetAmt = Number(newEntry.qty) * Number(newEntry.amt);
    newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []

    entries.value.splice(chooseLineIndex.value, 1, newEntry)

    chooseLineIndex.value = NaN
    chooseLineEntry.value = null
  }

  hideProductCharge.value = true
}

const productHandler = (newEntry, prod) => {
  newEntry.product = prod?.Name || ''
  newEntry.productId = prod?.id || ''
  newEntry.amt = prod?.M_ProductPrice?.PriceList || prod?.M_ProductPrice?.PriceStd || 0
  newEntry.charge = ''
  newEntry.chargeId = ''
  newEntry.lineNetAmt = Number(newEntry.qty) * Number(newEntry.amt);
  newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []
  hideProductCharge.value = true
}

const entryInOutLine = async (entry, opt) => {
  entry.product = opt?.M_Product_ID?.identifier || ''
  entry.productId = opt?.M_Product_ID?.id || ''
  entry.charge = ''
  entry.chargeId = ''
  entry.galleries = []
  if(entry.productId) {
    const response = await $fetch(`/api/materials/products/${entry.productId}`)
    if(response?.Strapi_Product_documentId) {
      const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
      if(resp) {
        entry.galleries = resp
      }
    }
  }
  hideProductCharge.value = true
}

const save = async () => {
  emit('update:modelValue', entries.value)
  emit('save', entries.value)
}
</script>

<template>
  <div class="lineTableResponsive card sd-none rd-0px bd-1px_solid_hexe4e3e6" @mouseleave="save">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Line</th>
            <th colspan="2">Product *</th>
            <th>Tax *</th>
            <th class="w-120px">Qty *</th>
            <th class="w-120px">Amt</th>
            <th class="w-120px">Line Amt</th>
            <th class="w-100px">Active</th>
            <th v-if="action !== 'view'" class="w-100px">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 8 : 7" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <template v-for="(entry, index) in entries" :key="index">
            <tr>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.line }}</span>
                <input v-else type="text" v-model="entry.line" class="input" />
              </td>
              <td>
                <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 v-if="entry.productId" src="https://placehold.co/40x40" alt="Placeholder Image" />
                  </div>
                </div>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.product }}</span>
                <ClientOnly v-else>
                  <ComboBox v-model="entry.productId" :options="products?.['products_'+index] || [{id: entry.productId, Name: entry.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterProducts('materials/products/filter', 'products_'+index)" @search="(val) => filterProducts('materials/products/filter', 'products_'+index, string.urlEncode(val))" @change="(val, opt) => productHandler(entry, opt)" :loading="loading?.['products_'+index] ?? true" class="groupItem" :up="true" type="slot" :select="true">
                    <template v-slot:default="{option, selected}">
                      <div class="d-flex justify-between gap-0.75rem">
                        <div class="flexGrow-1">
                          {{ option.Name }}
                        </div>
                        <div>
                          <div v-if="(option?.galleries?.length || 0) >= 1" class="productChooserBox" style="width: 32px; height: 32px;">
                            <img v-if="option?.galleries[0]?.formats?.small" :src="config.public.strapi+'/files-api/'+option?.galleries[0]?.formats?.small?.hash + option?.galleries[0]?.formats?.small?.ext" :alt="option?.galleries[0]?.name" />
                            <img v-else :src="config.public.strapi+'/files-api/'+option?.galleries[0]?.formats?.thumbnail?.hash + option?.galleries[0]?.formats?.thumbnail?.ext" :alt="option?.galleries[0]?.name" />
                          </div>
                          <div v-else class="productChooserBox" style="width: 32px; height: 32px;">
                            <img src="https://placehold.co/32x32" alt="Placeholder Image" />
                          </div>
                        </div>
                      </div>
                    </template>
                  </ComboBox>
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.tax }}</span>
                <ClientOnly v-else>
                  <SelectBox v-model="entry.taxId" :options="getOptions?.['taxes_'+index]?.records || [{id: entry.taxId, Name: entry.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_tax', 'taxes_'+index)" @search="(val) => filterOptions('c_tax', 'taxes_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['taxes_'+index] ?? true" :up="true" placeholder="----" />
                </ClientOnly>
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.qty }}</span>
                <input v-else type="text" v-model="entry.qty" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" />
              </td>
              <td>
                <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.amt }}</span>
                <input v-else type="text" v-model="entry.amt" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" />
              </td>
              <td>{{ entry.lineNetAmt }}</td>
              <td>
                <div class="check">
                  <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" :disabled="action === 'view'">
                  <label class="checkLabel" :for="'isActive_'+index">Active</label>
                </div>
              </td>
              <td v-if="action !== 'view'">
                <div class="d-flex justify-flexEnd gap-5px">
                  <span @click="entry.show = !entry.show;" 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 v-if="info.docStatusId !== 'CO'" @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                    <i class="menu-icon tf-icons ti ti-trash"></i>
                  </span>
                </div>
              </td>
            </tr>
            <tr v-if="entry?.show">
              <td :colspan="action !== 'view' ? 8 : 7">
                <div class="my-5 mx-5">
                  <AlertAction v-model='entry.alert.status' :alert="entry.alert" />
                  <div class="columns">
                    <div class="column is-two-thirds">
                      <div class="columns">
                        <div class="column is-half">
                          <label class="label d-block">Line</label>
                          <input type="text" v-model="entry.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                          <label class="label d-block mt-2">Product</label>
                          <div class="d-flex gap-10px">
                            <input type="text" v-model="entry.product" class="input flexGrow-1" readonly />
                            <template v-if="entry.inOutLineId === ''">
                              <button v-if="action !== 'view' && info.docStatusId !== 'CO'" type="button" class="button" @click="chooseLineIndex = index; chooseLineEntry = entry; showProductChooser = true;">Choose</button>
                            </template>
                          </div>

                          <label class="label d-block mt-2">Quantity *</label>
                          <input type="text" v-model="entry.qty" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                        </div>
                        <div class="column is-half">
                          <div :class="(action === 'view' || info.docStatusId !== 'DR') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block">Shipment/Receipt Line</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.inOutLineId" :options="getOptions?.['inoutlines_'+index]?.records || [{id: entry.inOutLineId, name: entry.inOutLine}]" prop="name" dataprop="id" datatype="string" :size="5" @click="filterOptions('m_inoutline', 'inoutlines_'+index, string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true`))" @search="(val) => filterOptions('m_inoutline', 'inoutlines_'+index, string.urlEncode(`M_InOut_ID eq ${info.inOutId} AND isActive eq true AND contains(Line,'${val}')`))" @change="(val, opt) => entryInOutLine(entry, opt)" :loading="loading?.['inoutlines_'+index] ?? true" placeholder="----" />
                            </ClientOnly>
                          </div>

                          <div :class="(hideProductCharge || action === 'view' || entry.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Charge</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.chargeId" :options="getOptions?.['charges_'+index]?.records || [{id: entry.chargeId, Name: entry.charge}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_charge', 'charges_'+index)" @search="(val) => filterOptions('c_charge', 'charges_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['charges_'+index] ?? true" />
                            </ClientOnly>
                          </div>
                          
                          <label class="label d-block mt-2">Amount</label>
                          <input type="text" v-model="entry.amt" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt);" class="input" :readonly="action === 'view' || info.docStatusId !== 'DR'" />
                        </div>
                      </div>
                      
                      <div class="columns">
                        <div class="column is-half">
                          <div :class="(action === 'view' || info.docStatusId !== 'DR') ? 'pointerEvents-none opacity-0.6' : ''">
                            <label class="label d-block mt-2">Tax</label>
                            <ClientOnly>
                              <SelectBox v-model="entry.taxId" :options="getOptions?.['taxes_'+index]?.records || [{id: entry.taxId, Name: entry.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_tax', 'taxes_'+index)" @search="(val) => filterOptions('c_tax', 'taxes_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['taxes_'+index] ?? true" placeholder="----" />
                            </ClientOnly>
                          </div>
                        </div>
                        <div class="column is-half">
                          <label class="label d-block mt-2">Line Amount</label>
                          <input type="text" :value="entry.lineNetAmt" class="input" readonly />
                        </div>
                      </div>

                      <label class="label d-block mt-2">Description</label>
                      <textarea v-model="entry.description" class="input" :disabled="action === 'view' || info.docStatusId === 'CO'"></textarea>
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block">Tenant</label>
                      <input type="text" :value="entry.client" class="input" readonly />

                      <label class="label d-block">Organization</label>
                      <input type="text" :value="entry.organization" class="input" readonly />

                      <label class="label d-block">Customer RMA</label>
                      <input type="text" :value="entry.rma" class="input" readonly />

                      <label class="label d-block">Status</label>
                      <div class="d-flex flexDirection-column">
                        <div class="check">
                          <input type="checkbox" v-model="entry.isActive" class="checkInput" id="isActive" :checked="entry.isActive" :disabled="action === 'view' || info.docStatusId === 'CO'">
                          <label class="checkLabel" for="isActive">Active</label>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </template>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="addLine" class="button">Add Line</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <ProductChooser v-model="showProductChooser" :info="info" @handler="productChooserHandler" />
  </Teleport>
</template>