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

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

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

const entries = ref([])
const highlightedRows = ref({})
const productInputRefs = ref([])
const selectedProductIndex = ref({}) // Track selected index for each picker
const keyboardHandlersAttached = ref({}) // Track which inputs have keyboard handlers attached

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 form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  warehouse: props.info?.warehouse || '',
  warehouseId: props.info?.warehouseId || '',
  order: props.info?.documentNo || '',
  orderId: props.info?.id || '',
  currency: props.info?.currency || '',
  currencyId: props.info?.currencyId || '',
  isActive: true,
  line: '',
  product: '',
  productId: '',
  gallery: {},
  galleries: [],
  qtyEntered: 1,
  qtyOrdered: 1,
  qtyReserved: 0.0,
  qtyDelivered: 0.0,
  qtyInvoiced: 0.0,
  uom: '',
  uomId: '',
  priceActual: 0,
  priceEntered: 0,
  priceList: 0,
  tax: '',
  taxId: '',
  discount: 0,
  lineNetAmt: 0,
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  charge: '',
  chargeId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  show: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.warehouse = props.info?.warehouse || ''
  form.value.warehouseId = props.info?.warehouseId || ''
  form.value.order = props.info?.documentNo || ''
  form.value.orderId = props.info?.id || ''
  form.value.currency = props.info?.currency || ''
  form.value.currencyId = props.info?.currencyId || ''
})

const addLine = () => {
  const newEntry = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    warehouse: props.info?.warehouse || '',
    warehouseId: props.info?.warehouseId || '',
    order: props.info?.documentNo || '',
    orderId: props.info?.id || '',
    currency: props.info?.currency || '',
    currencyId: props.info?.currencyId || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qtyEntered: 1,
    qtyOrdered: 1,
    qtyReserved: 0.0,
    qtyDelivered: 0.0,
    qtyInvoiced: 0.0,
    uom: '',
    uomId: '',
    priceActual: 0,
    priceEntered: 0,
    priceList: 0,
    tax: '',
    taxId: '',
    discount: 0,
    lineNetAmt: 0,
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    charge: '',
    chargeId: '',
    project: '',
    projectId: '',
    campaign: '',
    campaignId: '',
    show: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }

  entries.value.push(newEntry)
}

const showDetailRecordModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    warehouse: props.info?.warehouse || '',
    warehouseId: props.info?.warehouseId || '',
    order: props.info?.documentNo || '',
    orderId: props.info?.id || '',
    currency: props.info?.currency || '',
    currencyId: props.info?.currencyId || '',
    isActive: true,
    line: lineNumber.value,
    product: '',
    productId: '',
    gallery: {},
    galleries: [],
    qtyEntered: 1,
    qtyOrdered: 1,
    qtyReserved: 0.0,
    qtyDelivered: 0.0,
    qtyInvoiced: 0.0,
    uom: '',
    uomId: '',
    priceActual: 0,
    priceEntered: 0,
    priceList: 0,
    tax: '',
    taxId: '',
    discount: 0,
    lineNetAmt: 0,
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    charge: '',
    chargeId: '',
    project: '',
    projectId: '',
    campaign: '',
    campaignId: '',
    show: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}

const loading = ref({})
const filtering = ref({})
const products = ref({})
const getOptions = ref({})

// Helper function to clean up all picker states
const closeAllPickers = () => {
  // Remove active class from all pickers
  const pickers = document.querySelectorAll('.picker')
  pickers.forEach(picker => {
    picker.classList.remove('active')
  })

  // Hide all backdrops
  const pickerBackdrops = document.querySelectorAll('.pickerBackdrop')
  pickerBackdrops.forEach(backdrop => {
    backdrop.style.display = 'none'
  })

  // Blur any active element
  if (document.activeElement && document.activeElement.tagName === 'INPUT') {
    document.activeElement.blur()
  }
}

// Handle arrow key navigation in product picker
const handleProductKeyNavigation = (event, key, entry) => {
  const productList = products.value[key]
  if (!productList || productList.length === 0) return

  // Initialize selected index if not exists
  if (!selectedProductIndex.value[key] && selectedProductIndex.value[key] !== 0) {
    selectedProductIndex.value[key] = -1
  }

  if (event.key === 'ArrowDown') {
    event.preventDefault()
    selectedProductIndex.value[key] = Math.min(
      selectedProductIndex.value[key] + 1,
      productList.length - 1
    )
    scrollToSelectedProduct(key)
  } else if (event.key === 'ArrowUp') {
    event.preventDefault()
    selectedProductIndex.value[key] = Math.max(
      selectedProductIndex.value[key] - 1,
      0
    )
    scrollToSelectedProduct(key)
  } else if (event.key === 'Enter') {
    event.preventDefault()
    const selectedIndex = selectedProductIndex.value[key]
    if (selectedIndex >= 0 && selectedIndex < productList.length) {
      // Select the highlighted product
      productHandler(entry, productList[selectedIndex])
      closeAllPickers()
      // Reset selected index
      selectedProductIndex.value[key] = -1
    } else if (productList.length === 1) {
      // If only one product, select it
      productHandler(entry, productList[0])
      closeAllPickers()
      selectedProductIndex.value[key] = -1
    }
  } else if (event.key === 'Escape') {
    event.preventDefault()
    closeAllPickers()
    selectedProductIndex.value[key] = -1
  }
}

// Scroll to the selected product in the dropdown and highlight it
const scrollToSelectedProduct = (key) => {
  nextTick(() => {
    const index = key.startsWith('products_') ? parseInt(key.replace('products_', '')) : -1
    if (index >= 0) {
      // Find the active picker
      const row = document.querySelector(`tbody tr:nth-child(${index + 1})`)
      if (!row) return

      const picker = row.querySelector('.picker.suggestion')
      if (!picker) return

      const pickerContent = picker.querySelector('.pickerContent')
      if (!pickerContent) return

      // Get all picker items
      const allItems = pickerContent.querySelectorAll('.pickerItem')
      if (allItems.length === 0) return

      // Remove previous keyboard-selected class from all items
      allItems.forEach(item => item.classList.remove('keyboard-selected'))

      // Add keyboard-selected to the current item
      const selectedItem = allItems[selectedProductIndex.value[key]]
      if (selectedItem) {
        selectedItem.classList.add('keyboard-selected')
        selectedItem.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
      }
    }
  })
}

// Global keyboard handler that works for all product inputs
const setupGlobalKeyboardHandler = () => {
  // Use event delegation on document level
  document.addEventListener('keydown', (event) => {
    // Check if the active element is a product search input
    const activeElement = document.activeElement
    if (!activeElement || activeElement.tagName !== 'INPUT') return

    // Check if this input is inside a product picker
    const pickerContainer = activeElement.closest('.picker.suggestion')
    if (!pickerContainer) return

    // Find which row this belongs to by looking at the table structure
    const row = activeElement.closest('tr')
    if (!row) return

    // Get the row index
    const table = row.closest('tbody')
    if (!table) return

    const allRows = Array.from(table.querySelectorAll('tr')).filter(r => !r.querySelector('[colspan]'))
    const rowIndex = allRows.indexOf(row)

    if (rowIndex === -1) return

    const key = 'products_' + rowIndex
    const entry = entries.value[rowIndex]
    const productList = products.value[key]

    if (!productList || productList.length === 0) return

    // Initialize selected index if not exists
    if (selectedProductIndex.value[key] === undefined || selectedProductIndex.value[key] === null) {
      selectedProductIndex.value[key] = -1
    }

    if (event.key === 'ArrowDown') {
      event.preventDefault()
      event.stopPropagation()

      // If nothing is selected yet, select the first item
      if (selectedProductIndex.value[key] === -1) {
        selectedProductIndex.value[key] = 0
      } else {
        selectedProductIndex.value[key] = Math.min(
          selectedProductIndex.value[key] + 1,
          productList.length - 1
        )
      }

      scrollToSelectedProduct(key)
    } else if (event.key === 'ArrowUp') {
      event.preventDefault()
      event.stopPropagation()

      selectedProductIndex.value[key] = Math.max(
        selectedProductIndex.value[key] - 1,
        0
      )

      scrollToSelectedProduct(key)
    } else if (event.key === 'Enter') {
      const selectedIndex = selectedProductIndex.value[key]
      if (selectedIndex >= 0 && selectedIndex < productList.length) {
        event.preventDefault()
        event.stopPropagation()
        // Select the highlighted product
        productHandler(entry, productList[selectedIndex])
        closeAllPickers()
        // Reset selected index
        selectedProductIndex.value[key] = -1
      }
    } else if (event.key === 'Escape') {
      event.preventDefault()
      event.stopPropagation()
      closeAllPickers()
      selectedProductIndex.value[key] = -1
    }
  }, true) // Use capture phase
}

// Setup global handler on mount
onMounted(() => {
  setupGlobalKeyboardHandler()
})

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

    if(key.startsWith('products_')) {
      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

      // Auto-select if only one result after filtering and filter is not empty
      if(filter && products.value[key] && products.value[key].length === 1) {
        const entry = key.startsWith('products_') ? entries.value[parseInt(key.replace('products_', ''))] : null
        if(entry) {
          productHandler(entry, products.value[key][0])
        }
      }
      // Only show dropdown if filter has at least 3 characters and there are results
      else if(filter && filter.length >= 3 && products.value[key] && products.value[key].length > 0) {
        // Get the index from the key (products_X)
        const index = key.startsWith('products_') ? parseInt(key.replace('products_', '')) : -1
        if(index >= 0) {
          // Use nextTick to ensure the DOM has updated with the new products
          nextTick(() => {
            // Try to find the picker for this product field
            const productField = document.querySelector(`tr:nth-child(${index + 1}) td:nth-child(3) .groupItem .pickerInput`)
            if(productField) {
              // Find the closest picker container
              const pickerContainer = productField.closest('.picker')
              if(pickerContainer) {
                // Add active class to show the dropdown
                pickerContainer.classList.add('active')

                // Find and show the backdrop
                const backdrop = document.querySelector('.pickerBackdrop')
                if(backdrop) {
                  backdrop.style.display = 'block'
                }
              }
            }
          })
        }
      }
    }
  }
  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 newOrganizationId = isNaN(props.info?.organizationId) === false ? props.info?.organizationId : organizationId.value
  const newWarehouseId = props.info?.warehouseId || warehouseId.value

  // Reset selected index when user types to search
  if (filter) {
    selectedProductIndex.value[key] = -1
  }

  // Only search if filter has at least 3 characters
  if(filter && filter.length < 3) {
    return
  }

  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}&org_id=${newOrganizationId}`, key, filter)
        filtering.value[key] = filter

        // Force show dropdown after search with filter
        forceShowDropdown(key)
      }
    }
  } else {
    if(filter) {
      await setOptions(`${url}?m_warehouse_id=eq.${newWarehouseId}&name=fts.${filter}&org_id=${newOrganizationId}`, key, filter)
      filtering.value[key] = filter

      // Force show dropdown after search with filter
      forceShowDropdown(key)
    }
  }
}

// Helper function to force show dropdown
const forceShowDropdown = (key) => {
  // Use a longer timeout to ensure DOM has updated and data is loaded
  setTimeout(() => {
    try {
      // Get the index from the key (products_X)
      const index = key.startsWith('products_') ? parseInt(key.replace('products_', '')) : -1
      if(index >= 0) {
        // Try multiple selector approaches to find the picker
        const selectors = [
          `tr:nth-child(${index + 1}) td:nth-child(3) .groupItem .pickerInput`,
          `tr:nth-child(${index + 1}) td:nth-child(3) .groupItem input`,
          `tr:nth-child(${index + 1}) .picker`,
          `.picker`
        ]

        let pickerContainer = null

        // Try each selector until we find a match
        for (const selector of selectors) {
          const element = document.querySelector(selector)
          if (element) {
            // If we found an input, look for its parent picker
            if (element.tagName === 'INPUT') {
              pickerContainer = element.closest('.picker')
            } else {
              pickerContainer = element
            }

            if (pickerContainer) break
          }
        }

        if (pickerContainer) {
          // Add active class to show the dropdown
          pickerContainer.classList.add('active')

          // Find and show the backdrop
          const backdrop = document.querySelector('.pickerBackdrop')
          if (backdrop) {
            backdrop.style.display = 'block'
          }

          console.log('Dropdown forced to show for key:', key)
        } else {
          console.log('Could not find picker container for key:', key)
        }
      }
    } catch (error) {
      console.error('Error forcing dropdown to show:', error)
    }
  }, 300) // Increased timeout for better reliability
}

const checkLineChanged = ref({})
const retrieve = async () => {
  const newId = route.params?.id || props.info?.id || null
  if(newId) {
    const res = await $fetch('/api/orders/'+newId+'/order-line', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          warehouse: item?.M_Warehouse_ID?.identifier || '',
          warehouseId: item?.M_Warehouse_ID?.id || '',
          order: item?.C_Order_ID?.identifier || '',
          orderId: item?.C_Order_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: [],
          qtyEntered: item?.QtyEntered || 1,
          qtyOrdered: item?.QtyOrdered || 1,
          qtyReserved: item?.QtyReserved || 0.0,
          qtyDelivered: item?.QtyDelivered || 0.0,
          qtyInvoiced: item?.QtyInvoiced || 0.0,
          uom: item?.C_UOM_ID?.identifier || '',
          uomId: item?.C_UOM_ID?.id || '',
          priceActual: item?.PriceActual || 0,
          priceEntered: item?.PriceEntered || 0,
          priceList: item?.PriceList || 0,
          tax: item?.C_Tax_ID?.identifier || '',
          taxId: item?.C_Tax_ID?.id || '',
          discount: item?.Discount || 0,
          lineNetAmt: item?.LineNetAmt || 0,
          currency: item?.C_Currency_ID?.identifier || '',
          currencyId: item?.C_Currency_ID?.id || '',
          attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
          attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
          charge: item?.C_Charge_ID?.identifier || '',
          chargeId: item?.C_Charge_ID?.id || '',
          project: item?.C_Project_ID?.identifier || '',
          projectId: item?.C_Project_ID?.id || '',
          campaign: item?.C_Campaign_ID?.identifier || '',
          campaignId: item?.C_Campaign_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) {
        checkLineChanged.value[item.id] = item.lineNetAmt
        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(products.value?.['products_'+index]) {
    products.value['products_'+index] = []
  }

  if(entry.id) {
    await $fetch('/api/orders/'+entry.id+'/order-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.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
    newEntry.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
    newEntry.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
    newEntry.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    newEntry.charge = ''
    newEntry.chargeId = ''
    newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);
    newEntry.gallery = prod?.gallery ?? {}
    newEntry.galleries = prod?.galleries ?? []

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

    chooseLineIndex.value = NaN
    chooseLineEntry.value = null
  } else {
    form.value.product = prod?.Name || ''
    form.value.productId = prod?.id || ''
    form.value.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
    form.value.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
    form.value.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
    form.value.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    form.value.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
    form.value.charge = ''
    form.value.chargeId = ''
    form.value.gallery = prod?.gallery ?? {}
    form.value.galleries = prod?.galleries ?? []
  }
  hideProductCharge.value = true
}

const productHandler = (newEntry, prod) => {
  newEntry.product = prod?.Name || ''
  newEntry.productId = prod?.id || ''
  newEntry.uom = prod?.uom_name || prod?.C_UOM_ID?.identifier || ''
  newEntry.uomId = prod?.c_uom_id || prod?.C_UOM_ID?.id || ''
  newEntry.priceActual = prod?.product_price || prod?.M_ProductPrice?.PriceStd || 0
  newEntry.priceEntered = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
  newEntry.priceList = prod?.product_price || prod?.M_ProductPrice?.PriceList || 0
  newEntry.charge = ''
  newEntry.chargeId = ''
  newEntry.lineNetAmt = Number(newEntry.qtyEntered) * Number(newEntry.priceEntered);
  newEntry.gallery = prod?.gallery ?? {}
  newEntry.galleries = prod?.galleries ?? []
  hideProductCharge.value = true

  // Find the index of the entry in the entries array
  const index = entries.value.findIndex(entry => entry === newEntry)
  if (index !== -1) {
    // Set the highlight for this row
    highlightedRows.value[index] = true

    // Remove the highlight after 2 seconds
    setTimeout(() => {
      highlightedRows.value[index] = false
    }, 2000)

    // Reset selected product index for this picker
    const key = 'products_' + index
    selectedProductIndex.value[key] = -1
  }

  // Close all pickers after selection
  closeAllPickers()
}


const enterProductHandler = (newEntry, key) => {
  const prod = products.value[key]
  if(prod && prod.length === 1) {
    productHandler(newEntry, prod[0])
    // productHandler now calls closeAllPickers()
  } else if(prod && prod.length > 0) {
    // If there are multiple products, we'll keep the dropdown open
    // The user can then select one or refine their search

    // Get the index from the key (products_X)
    const index = key.startsWith('products_') ? parseInt(key.replace('products_', '')) : -1
    if(index >= 0) {
      // Use nextTick to ensure the DOM has updated with the new products
      nextTick(() => {
        // Try to find the picker for this product field
        const productField = document.querySelector(`tr:nth-child(${index + 1}) td:nth-child(3) .groupItem .pickerInput`)
        if(productField) {
          // Find the closest picker container
          const pickerContainer = productField.closest('.picker')
          if(pickerContainer) {
            // Add active class to show the dropdown
            pickerContainer.classList.add('active')

            // Find and show the backdrop
            const backdrop = document.querySelector('.pickerBackdrop')
            if(backdrop) {
              backdrop.style.display = 'block'
            }
          }
        }
      })
    }
  } else {
    // No products found, close picker
    closeAllPickers()
  }
}

const saveAll = async () => {
  // Use Promise.all to wait for all saves to complete
  await Promise.all(entries.value.map(async (item) => {
    await save(item, false)
  }))
  // Then retrieve the updated data
  await retrieve()
}

const save = async (entry = null, saveOnlyOne = true) => {
  const newEntry = entry ?? unref(form.value)

  if(newEntry.id !== '') {
    const res = await $fetch('/api/orders/'+route.params.id+'/order-line', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: newEntry.id,
        isActive: newEntry.isActive,
        line: newEntry.line,
        //productId: newEntry.productId,
        qtyEntered: newEntry.qtyEntered,
        qtyOrdered: newEntry.qtyOrdered,
        uomId: newEntry.uomId,
        priceActual: newEntry.priceActual,
        priceEntered: newEntry.priceEntered,
        priceList: newEntry.priceList,
        tax: newEntry.tax,
        taxId: newEntry.taxId,
        discount: newEntry.discount,
        lineNetAmt: newEntry.lineNetAmt,
        warehouseId: newEntry.warehouseId,
        currencyId: newEntry.currencyId,
        attributeSetInstanceId: newEntry.attributeSetInstanceId,
        chargeId: newEntry.chargeId,
        projectId: newEntry.projectId,
        campaignId: newEntry.campaignId,
      }
    })
    if(Number(res.status) === 200) {
      // Update checkLineChanged to reflect the saved state
      if (newEntry.id) {
        // Create a new object to ensure reactivity
        const newCheckLineChanged = { ...checkLineChanged.value }
        newCheckLineChanged[newEntry.id] = newEntry.lineNetAmt
        checkLineChanged.value = newCheckLineChanged
        console.log('Updated checkLineChanged for entry ID:', newEntry.id)
      }

      closeDetailRecordModal()
      if(saveOnlyOne) {
        retrieve()
      }
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/orders/'+route.params.id+'/order-line', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: newEntry.organizationId || organizationId.value,
        orderId: route.params.id,
        isActive: newEntry.isActive,
        line: newEntry.line,
        productId: newEntry.productId,
        qtyEntered: newEntry.qtyEntered,
        qtyOrdered: newEntry.qtyOrdered,
        uomId: newEntry.uomId,
        priceActual: newEntry.priceActual,
        priceEntered: newEntry.priceEntered,
        priceList: newEntry.priceList,
        tax: newEntry.tax,
        taxId: newEntry.taxId,
        discount: newEntry.discount,
        lineNetAmt: newEntry.lineNetAmt,
        warehouseId: newEntry.warehouseId,
        currencyId: newEntry.currencyId,
        attributeSetInstanceId: newEntry.attributeSetInstanceId,
        chargeId: newEntry.chargeId,
        projectId: newEntry.projectId,
        campaignId: newEntry.campaignId,
      }
    })
    if(Number(res.status) === 200) {
      // Update the entry with the ID returned from the server
      if(res.id) {
        newEntry.id = res.id
        // Update checkLineChanged for the newly created entry
        const newCheckLineChanged = { ...checkLineChanged.value }
        newCheckLineChanged[res.id] = newEntry.lineNetAmt
        checkLineChanged.value = newCheckLineChanged
      }

      closeDetailRecordModal()
      if(saveOnlyOne) {
        retrieve()
      }
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}

const showAttachmentViewer = ref(false)
const showAttachmentViewerData = ref({})
const viewAttachmentViewer = (fileData) => {
  showAttachmentViewer.value = true
  showAttachmentViewerData.value = fileData
}
watch(showAttachmentViewer, () => {
  if(!showAttachmentViewer.value) {
    showAttachmentViewerData.value = {}
  }
})

const csvNo = ref(1)
const addLineByCSV = async (csvItem, csvLength) => {
  const res = await $fetch(`/api/materials/products/${csvItem[0]}/sku?org_id=${props.info?.organizationId || organizationId.value || 11}`)
  if(res?.id) {
    let galleries = []
    let gallery = {}
    if(res?.Strapi_Product_documentId) {
      const resp = await $fetch(`/api/materials/products/${res.Strapi_Product_documentId}/galleries`)
      if(resp?.data) {
        galleries = resp.data?.image ?? []
        gallery = filterProductGallery(galleries, resp.data)
      }
    }

    entries.value.push({
      id: '',
      client: props.info?.client || '',
      clientId: props.info?.clientId || '',
      organization: props.info?.organization || '',
      organizationId: props.info?.organizationId || organizationId.value || '',
      warehouse: props.info?.warehouse || '',
      warehouseId: props.info?.warehouseId || '',
      order: props.info?.documentNo || '',
      orderId: props.info?.id || '',
      currency: props.info?.currency || '',
      currencyId: props.info?.currencyId || '',
      isActive: true,
      line: lineNumber.value,
      product: res?.Name || csvItem[1],
      productId: res.id || '',
      gallery: gallery,
      galleries: galleries,
      qtyEntered: Number(csvItem[2] || 1),
      qtyOrdered: Number(csvItem[2] || 1),
      qtyReserved: 0.0,
      qtyDelivered: 0.0,
      qtyInvoiced: 0.0,
      uom: res?.C_UOM_ID?.identifier || '',
      uomId: res?.C_UOM_ID?.id || '',
      priceActual: res?.m_productprice?.[0]?.PriceStd || 0,
      priceEntered: res?.m_productprice?.[0]?.PriceStd || 0,
      priceList: res?.m_productprice?.[0]?.PriceLimit || 0,
      tax: '',
      taxId: '',
      discount: 0,
      lineNetAmt: Number(csvItem[2] || 1) * Number(res?.m_productprice?.[0]?.PriceStd || 0),
      attributeSetInstance: '',
      attributeSetInstanceId: '',
      charge: '',
      chargeId: '',
      project: '',
      projectId: '',
      campaign: '',
      campaignId: '',
      show: false,
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    })

    csvNo.value++
  }

  if(csvNo.value >= csvLength) {
    saveAll()
  }
}

const tabQtyHandler = async (entry, index) => {
  console.log('Tab pressed in Qty field, saving entry:', entry)

  // Make sure the lineNetAmt is calculated correctly
  entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered)

  // First save the current entry
  try {
    await save(entry, false)
    console.log('Entry saved successfully')

    // Update checkLineChanged to reflect the saved state
    if (entry.id) {
      // Create a new object to ensure reactivity
      const newCheckLineChanged = { ...checkLineChanged.value }
      newCheckLineChanged[entry.id] = entry.lineNetAmt
      checkLineChanged.value = newCheckLineChanged
      console.log('Updated checkLineChanged for entry ID:', entry.id)
      console.log('Debug - entry.id:', entry.id)
      console.log('Debug - entry.lineNetAmt:', entry.lineNetAmt)
      console.log('Debug - checkLineChanged[entry.id]:', checkLineChanged.value[entry.id])
      console.log('Debug - Are they equal?', entry.lineNetAmt === checkLineChanged.value[entry.id])
    }
  } catch (error) {
    console.error('Error saving entry:', error)
    // Show error toast
    toast({
      message: 'Error saving entry: ' + (error.message || 'Unknown error'),
      type: 'is-danger',
      duration: 2000
    })
    return // Don't proceed if save failed
  }

  // Add a new line
  addLine()

  // Get the index of the newly created line
  const newIndex = entries.value.length - 1

  // Don't highlight the new row when created via Tab key
  // as no product is saved yet
  highlightedRows.value[newIndex] = false

  // Use nextTick to ensure the DOM has updated
  await nextTick()

  // Wait a bit more to ensure the ComboBox is fully initialized
  setTimeout(() => {
    console.log('Focusing on product field for new line:', newIndex)

    // Try to use the ref to access the ComboBox component
    if (productInputRefs.value[newIndex]) {
      console.log('Found product field via ref, focusing now')

      // If the ComboBox component has a focus method
      if (typeof productInputRefs.value[newIndex].focus === 'function') {
        productInputRefs.value[newIndex].focus()
      }
      // If we need to access the input element inside the ComboBox
      else if (productInputRefs.value[newIndex].$el) {
        const input = productInputRefs.value[newIndex].$el.querySelector('input')
        if (input) {
          input.focus()
          input.click() // Also trigger click to open the dropdown
        }
      }
    } else {
      console.log('Could not find product field via ref, trying DOM selectors')

      // Try to find the ComboBox input field using DOM selectors
      const productField = document.querySelector(`tr:nth-child(${newIndex + 1}) td:nth-child(3) .groupItem input`)

      if (productField) {
        console.log('Found product field by selector, focusing now')
        productField.focus()
        productField.click() // Also trigger click to open the dropdown
      } else {
        console.log('Could not find product field by selector, trying alternative methods')

        // Try alternative selectors
        const allInputs = document.querySelectorAll('tr .groupItem input')
        console.log('Total ComboBox inputs found:', allInputs.length)

        if (allInputs.length > 0) {
          const lastInput = allInputs[allInputs.length - 1]
          console.log('Focusing on last ComboBox input')
          lastInput.focus()
          lastInput.click()
        }
      }
    }
  }, 200) // Increased timeout for better reliability
}

const csvFiles = ref([])
const handleCSVFiles = (files) => {
  for(let file of files) {
    const reader = new FileReader()
    reader.onload = () => {
      const csvContent = reader.result.split('\r\n').map(line => {
        return line.split(';')
      })
      for(let csvArr of csvContent) {
        if(csvArr) {
          addLineByCSV(csvArr, csvContent.length)
        }
      }
    }
    reader.onerror = () => {
      alert('Error reading the file. Please try again.');
    }
    reader.readAsText(file)
  }

  csvFiles.value = []
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
        <tr>
          <th>Line</th>
          <th colspan="2">Product</th>
          <th>Unit</th>
          <th class="w-120px">Qty</th>
          <th class="w-120px">Price</th>
          <th class="w-120px">Amount</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 :class="{ 'highlight-row': highlightedRows[index] }">
            <td>
              <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.line }}</span>
              <input v-else type="text" v-model="entry.line" @keydown.enter="save(entry)" class="input" />
            </td>
            <td>
              <div>
                <div v-if="entry?.gallery?.id" @click="viewAttachmentViewer(entry?.gallery ?? {})">
                  <div class="productChooserBox" style="width: 40px; height: 40px;">
                    <img v-if="entry?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.small?.hash + entry?.gallery?.formats?.small?.ext" :alt="entry?.gallery?.name" />
                    <img v-else :src="config.public.strapi+'/files-api/'+entry?.gallery?.formats?.thumbnail?.hash + entry?.gallery?.formats?.thumbnail?.ext" :alt="entry?.gallery?.name" />
                  </div>
                </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 style="vertical-align: middle; max-width: 400px;">
              <ContextMenu v-model="entry.productId" :items="[(entry.productId ? 'zoom' : 'clear')]" :info="{windowFrom: 'zoom', toPath: '/windows/materials-products-edit/'+entry.productId, pathName: 'Product: '+entry.product}">
                <div>
                  <span v-if="action === 'view' || info.docStatusId === 'CO' || entry.id !== ''">{{ entry.product }}</span>
                  <ComboBox v-else v-model="entry.productId" :options="products?.['products_'+index] || []" prop="Name" dataprop="id" datatype="string" :size="5" @search="(val) => filterProducts('materials/products/filter-elastic', 'products_'+index, string.urlEncode(val))" @change="(val, opt) => productHandler(entry, opt)" :loading="loading?.['products_'+index] ?? true" class="groupItem" :up="true" type="slot" :select="true" @enter="enterProductHandler(entry, 'products_'+index)" :ref="el => { productInputRefs[index] = el }">
                    <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?.gallery?.id" class="productChooserBox" style="width: 32px; height: 32px;">
                            <img v-if="option?.gallery?.formats?.small" :src="config.public.strapi+'/files-api/'+option?.gallery?.formats?.small?.hash + option?.gallery?.formats?.small?.ext" :alt="option?.gallery?.name" />
                            <img v-else :src="config.public.strapi+'/files-api/'+option?.gallery?.formats?.thumbnail?.hash + option?.gallery?.formats?.thumbnail?.ext" :alt="option?.gallery?.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>
                </div>
              </ContextMenu>
            </td>
            <td>
              <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.uom }}</span>
              <ClientOnly v-else>
                <SelectBox v-model="entry.uomId" :options="getOptions?.['units_'+index]?.records || [{id: entry.uomId, Name: entry.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_uom', 'units_'+index)" @search="(val) => filterOptions('c_uom', 'units_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['units_'+index] ?? true" :up="true" placeholder="----" />
              </ClientOnly>
            </td>
            <td>
              <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.qtyEntered }}</span>
              <input v-else type="text" v-model="entry.qtyEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered); entry.qtyOrdered = entry.qtyEntered;" @keydown.enter="save(entry)" @keydown.tab.prevent="tabQtyHandler(entry, index)" class="input qty-input" :data-index="index" />
            </td>
            <td>
              <span v-if="action === 'view' || info.docStatusId === 'CO'">{{ entry.priceEntered }}</span>
              <input v-else type="text" v-model="entry.priceEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" @keydown.enter="save(entry)" 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' || info.docStatusId === 'CO'">
                <label class="checkLabel" :for="'isActive_'+index">Active</label>
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                  <span v-if="info.docStatusId !== 'CO'" @click="save(entry)" class="cursor-pointer fg-success">
                    <i class="menu-icon tf-icons ti ti-device-floppy" :class="{redIcon: entry.id === '' || String(checkLineChanged[entry.id]) !== String(entry.lineNetAmt)}"></i>
                  </span>
                <span @click="entry.show = !entry.show" class="cursor-pointer fg-success">
                    <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="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                    <i v-if="info.docStatusId === 'CO'" class="menu-icon tf-icons ti ti-eye"></i>
                    <i v-else class="menu-icon tf-icons ti ti-pencil"></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">
                <div class="columns">
                  <div class="column is-two-thirds">
                    <label class="label d-block">Line</label>
                    <input type="text" v-model="entry.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                    <div class="columns">
                      <div class="column is-half">
                        <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 />
                          <button v-if="action !== 'view' && info.docStatusId !== 'CO' && entry.id === ''" type="button" class="button" @click="chooseLineIndex = index; chooseLineEntry = entry; showProductChooser = true;">Choose</button>
                        </div>

                        <label class="label d-block mt-2">Attribute Set Instance</label>
                        <input type="text" class="input" readonly />
                      </div>
                      <div class="column is-half">
                        <div :class="(hideProductCharge || action === 'view' || info.docStatusId === 'CO' || entry.id !== '') ? '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">Resource Assignment</label>
                        <input type="text" 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 class="columns">
                      <div class="column is-half">
                        <label class="label d-block mt-2">Quantity *</label>
                        <input type="text" v-model="entry.qtyEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered); entry.qtyOrdered = entry.qtyEntered;" @keydown.enter="save(entry)" @keydown.tab.prevent="tabQtyHandler(entry, index)" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                        <label class="label d-block mt-2">Ordered Quantity *</label>
                        <input type="text" v-model="entry.qtyOrdered" class="input" readonly />

                        <label class="label d-block mt-2">Reserved Quantity *</label>
                        <input type="text" v-model="entry.qtyReserved" class="input" readonly />

                        <label class="label d-block mt-2">Shipper</label>
                        <input type="text" class="input" readonly />
                      </div>
                      <div class="column is-half">
                        <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                          <label class="label d-block mt-2">UOM *</label>
                          <ClientOnly>
                            <SelectBox v-model="entry.uomId" :options="getOptions?.['units_'+index]?.records || [{id: entry.uomId, Name: entry.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_uom', 'units_'+index)" @search="(val) => filterOptions('c_uom', 'units_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['units_'+index] ?? true" placeholder="----" />
                          </ClientOnly>
                        </div>

                        <label class="label d-block mt-2">Invoiced Quantity *</label>
                        <input type="text" v-model="entry.qtyInvoiced" class="input" readonly />

                        <label class="label d-block mt-2">Delivered Quantity *</label>
                        <input type="text" v-model="entry.qtyDelivered" class="input" readonly />
                      </div>
                    </div>

                    <label class="label d-block mt-2">Price *</label>
                    <input type="text" v-model="entry.priceEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered);" @keydown.enter="save(entry)" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                    <div class="columns">
                      <div class="column is-half">
                        <label class="label d-block mt-2">Unit Price *</label>
                        <input type="text" v-model="entry.priceActual" class="input" readonly />

                        <div :class="(action === 'view' || info.docStatusId === 'CO') ? '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 :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                          <label class="label d-block mt-2">Project</label>
                          <ClientOnly>
                            <SelectBox v-model="entry.projectId" :options="getOptions?.['projects_'+index]?.records || [{id: entry.projectId, Name: entry.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_project', 'projects_'+index)" @search="(val) => filterOptions('c_project', 'projects_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['projects_'+index] ?? true" placeholder="----" :up="true" />
                          </ClientOnly>
                        </div>
                      </div>
                      <div class="column is-half">
                        <label class="label d-block mt-2">List Price *</label>
                        <input type="text" v-model="entry.priceList" class="input" readonly />

                        <label class="label d-block mt-2">Discount %</label>
                        <input type="text" v-model="entry.discount" @keydown.enter="save(entry)" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                        <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                          <label class="label d-block mt-2">Campaign</label>
                          <ClientOnly>
                            <SelectBox v-model="entry.campaignId" :options="getOptions?.['campaigns_'+index]?.records || [{id: entry.campaignId, Name: entry.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('c_campaign', 'campaigns_'+index)" @search="(val) => filterOptions('c_campaign', 'campaigns_'+index, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['campaigns_'+index] ?? true" placeholder="----" :up="true" />
                          </ClientOnly>
                        </div>
                      </div>
                    </div>

                    <label class="label d-block mt-2">Line Amount</label>
                    <input type="text" v-model="entry.lineNetAmt" class="input" readonly />
                  </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">Warehouse</label>
                    <input type="text" :value="entry.warehouse" 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' && info.docStatusId !== 'CO'">
          <td colspan="5">
            <div class="d-flex gap-10px">
              <button type="button" @click="addLine" class="button">Add Line</button>
              <AttachBox v-model="csvFiles" @handler="handleCSVFiles" accept="text/csv">
                <button type="button" class="button pointerEvents-none">Add Line with CSV</button>
              </AttachBox>
              <button type="button" @click="showDetailRecordModal = true; form.line = lineNumber;" class="button">Advanced ADD</button>
              <button type="button" @click="saveAll" class="button" :class="{redButton: entries.filter(i => i.id === '' || String(checkLineChanged[i.id]) !== String(i.lineNetAmt)).length >= 1}">Save ALL</button>
            </div>
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Order Line</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody">
            <div class="my-5 mx-5">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns">
                <div class="column is-two-thirds">
                  <label class="label d-block">Line</label>
                  <input type="text" v-model="form.line" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Product</label>
                      <!--<ClientOnly>
                        <SelectBox v-model="form.productId" :options="getOptions?.['products']?.records || [{id: form.productId, Name: form.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" />
                      </ClientOnly>-->
                      <div class="d-flex gap-10px">
                        <input type="text" v-model="form.product" class="input flexGrow-1" readonly />
                        <button v-if="action !== 'view' && info.docStatusId !== 'CO' && form.id === ''" type="button" class="button" @click="showProductChooser = true">Choose</button>
                      </div>

                      <label class="label d-block mt-2">Attribute Set Instance</label>
                      <input type="text" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <div :class="(hideProductCharge || action === 'view' || info.docStatusId === 'CO' || form.id !== '') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Charge</label>
                        <ClientOnly>
                          <SelectBox v-model="form.chargeId" :options="getOptions?.['charges']?.records || [{id: form.chargeId, Name: form.charge}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_charge', 'charges')" :loading="loading?.['charges'] ?? true" />
                        </ClientOnly>
                      </div>

                      <label class="label d-block mt-2">Resource Assignment</label>
                      <input type="text" class="input" readonly />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input" :disabled="action === 'view' || info.docStatusId === 'CO'"></textarea>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Quantity *</label>
                      <input type="text" v-model="form.qtyEntered" @input="form.lineNetAmt = Number(form.qtyEntered) * Number(form.priceEntered); form.qtyOrdered = form.qtyEntered;" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                      <label class="label d-block mt-2">Reserved Quantity *</label>
                      <input type="text" v-model="form.qtyReserved" class="input" readonly />

                      <label class="label d-block mt-2">Shipper</label>
                      <input type="text" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">UOM *</label>
                        <ClientOnly>
                          <SelectBox v-model="form.uomId" :options="getOptions?.['units']?.records || [{id: form.uomId, Name: form.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'units')" :loading="loading?.['units'] ?? true" placeholder="----" />
                        </ClientOnly>
                      </div>

                      <label class="label d-block mt-2">Invoiced Quantity *</label>
                      <input type="text" v-model="form.qtyInvoiced" class="input" readonly />

                      <label class="label d-block mt-2">Delivered Quantity *</label>
                      <input type="text" v-model="form.qtyDelivered" class="input" readonly />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Price *</label>
                  <input type="text" v-model="form.priceEntered" @input="form.lineNetAmt = Number(form.qtyEntered) * Number(form.priceEntered);" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Unit Price *</label>
                      <input type="text" v-model="form.priceActual" class="input" readonly />

                      <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Tax *</label>
                        <ClientOnly>
                          <SelectBox v-model="form.taxId" :options="getOptions?.['taxes']?.records || [{id: form.taxId, Name: form.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_tax', 'taxes')" :loading="loading?.['taxes'] ?? true" placeholder="----" />
                        </ClientOnly>
                      </div>

                      <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Project</label>
                        <ClientOnly>
                          <SelectBox v-model="form.projectId" :options="getOptions?.['projects']?.records || [{id: form.projectId, Name: form.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_project', 'projects')" :loading="loading?.['projects'] ?? true" placeholder="----" :up="true" />
                        </ClientOnly>
                      </div>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">List Price *</label>
                      <input type="text" v-model="form.priceList" class="input" readonly />

                      <label class="label d-block mt-2">Discount %</label>
                      <input type="text" v-model="form.discount" class="input" :readonly="action === 'view' || info.docStatusId === 'CO'" />

                      <div :class="(action === 'view' || info.docStatusId === 'CO') ? 'pointerEvents-none opacity-0.6' : ''">
                        <label class="label d-block mt-2">Campaign</label>
                        <ClientOnly>
                          <SelectBox v-model="form.campaignId" :options="getOptions?.['campaigns']?.records || [{id: form.campaignId, Name: form.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_campaign', 'campaigns')" :loading="loading?.['campaigns'] ?? true" placeholder="----" :up="true" />
                        </ClientOnly>
                      </div>
                    </div>
                  </div>

                  <label class="label d-block mt-2">Line Amount</label>
                  <input type="text" v-model="form.lineNetAmt" class="input" readonly />
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Tenant</label>
                  <input type="text" :value="form.client" class="input" readonly />

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

                  <label class="label d-block">Warehouse</label>
                  <input type="text" :value="form.warehouse" class="input" readonly />

                  <label class="label d-block">Status</label>
                  <div class="d-flex flexDirection-column">
                    <div class="check">
                      <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive">
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button type="button" v-if="action !== 'view' && info.docStatusId !== 'CO'" class="button" @click="save(null)" :class="(form.productId === '') ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <POProductChooser v-model="showProductChooser" :info="info" @handler="productChooserHandler" />
    <AttachmentViewer v-model="showAttachmentViewer" :type="showAttachmentViewerData?.mime ?? ''" :source="(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url) ? config.public.strapi+'/files-api/'+(showAttachmentViewerData?.formats?.large?.url ?? showAttachmentViewerData?.url).replace('/uploads/', '') : ''" :title="showAttachmentViewerData?.name ?? ''" :width="showAttachmentViewerData?.width ?? 1366" :height="showAttachmentViewerData?.height ?? 768" />
  </Teleport>
</template>

<style scoped>
.highlight-row {
  animation: highlight-fade 2s ease-out;
}

@keyframes highlight-fade {
  0% {
    background-color: rgba(11, 193, 17, 0.8); /* Light green */
  }
  100% {
    background-color: transparent;
  }
}
</style>

<style>
/* Make the dropdown more visually distinct */
.picker.active .pickerDropdown {
  background-color: #f8f9fa !important;
  border: 1px solid #4285f4 !important;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1) !important;
}

.picker.active .pickerDropdown .pickerItem:hover {
  background-color: #e8f0fe !important;
}

.picker.active .pickerDropdown .pickerItem.selected {
  background-color: #4285f4 !important;
  color: white !important;
}

/* Keyboard navigation highlighting */
.keyboard-selected {
  background-color: #e8f0fe !important;
  border-left: 3px solid #4285f4 !important;
  padding-left: 8px !important;
}

/* Highlight row when product is selected */
.highlight-row {
  background-color: #e8f5e9 !important;
  transition: background-color 0.3s ease;
}
</style>
