<script setup>
const router = useRouter()
const url = useRequestURL()
const tabs = useTabs()

const props = defineProps({
  modelValue: Boolean,
  searchQuery: String
})


// Use the centralized role menu composable
const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')


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

const search = ref(props.searchQuery || '')
const searchRef = ref(null)
const searchTimer = ref(undefined)
const throttleSearch = () => {
  clearTimeout(searchTimer.value)
  searchTimer.value = setTimeout(() => {
    if(search.value !== '') {
      searchFetch(search.value)
    }
  }, 500)
}

const partners = ref([])
const products = ref([])
const orders = ref([])
const users = ref([])
const shipments = ref([])
const invoices = ref([])
const requests = ref([])

const searchFetch = async (query) => {
  const res = await $fetch(`/api/search/${query}`, {
    query: {
      defaultSideBarMenu: defaultSideBarMenu.value
    }
  })
  if(res) {
    // Log the complete response for debugging
    // console.log('=== SEARCH API COMPLETE RESPONSE ===', JSON.stringify(res, null, 2))

    partners.value = res.c_bpartner?.hits?.hits || []
    products.value = res.m_product?.hits?.hits || []
    orders.value = res.c_order?.hits?.hits || []
    users.value = res.ad_user?.hits?.hits || []
    shipments.value = res.m_inout?.hits?.hits || []
    invoices.value = res.c_invoice?.hits?.hits || []
    requests.value = res.r_request?.hits?.hits || []
  }
}

const showSearchModal = ref(props.modelValue ?? false)
watch(() => props.modelValue, () => {
  showSearchModal.value = props.modelValue
})
watch(showSearchModal, () => {
  setTimeout(() => {
    if(searchRef.value) {
      searchRef.value.focus()
    }
  }, 100)
})
watch(() => props.searchQuery, () => {
  search.value = props.searchQuery
  throttleSearch()
})
const closeSearchModal = () => {
  showSearchModal.value = false
  search.value = ''
  emit('update:modelValue', showSearchModal.value)
  emit('update:searchQuery', search.value)
}

const goTo = (toPath, pathName) => {
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === toPath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === toPath)
    tabs.value[tabIndex].active = true
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  closeSearchModal()
}

onMounted(() => {
  defaultSideBarMenu.value = getMenuType()
})

</script>

<template>
  <div class="modal" :class="{'active': showSearchModal}" :style="{display: showSearchModal ? 'block' : 'none'}">
    <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeSearchModal">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">Search</h3>
          <h4 class="smallsearchtitle">Zur erweiterten Suche "*" verwenden.</h4>
          <div class="cursor-pointer" @click="closeSearchModal">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>
        <div class="modalBody">
          <div class="d-flex justify-center items-center mb-3">
            <div class="group w-300px">
              <input ref="searchRef" type="search" v-model="search" @input="throttleSearch" class="input groupItem" @keyup.enter="throttleSearch" placeholder="Search here..." />
              <button type="button" class="button groupItem" @click="throttleSearch">
                <i class="pointerEvents-none menu-icon tf-icons ti ti-search fg-hexfff"></i>
              </button>
            </div>
          </div>
          <div>
            <div class="mt-0">
              <div class="columns is-desktop">
                <div class="column is-one-quarter">
                  <div class="list">
                    <div class="listHeader">
                      <strong class="fw-bold">Kunden</strong>
                    </div>
                    <div class="listMenu">
<!--                      <div v-for="item in partners" class="listItem" @click="goTo('/windows/partners-partners-edit/'+item._source.c_bpartner_id, 'Edit Partner')">{{ item?._source?.name }} <span class="smallsearchtext">{{ item?._source?.adorgname?.slice(0,3) }}</span> </div>-->
                      <div v-for="item in partners" class="listItem" @click="goTo('/windows/partners-partners-edit/'+item._source.c_bpartner_id, 'Edit Partner')">{{ item?._source?.name }} <span class="smallsearchtext">{{ item?._source?.ad_org_id }}</span> </div>

                    </div>
                  </div>
                </div>
                <div class="column is-one-quarter">
                  <div class="list">
                    <div class="listHeader">
                      <strong class="fw-bold">Produkte</strong>
                    </div>
                    <div class="listMenu">
                      <div v-for="item in products" class="listItem" @click="goTo('/windows/materials-products-edit/'+item._source.m_product_id, 'Edit Product')">{{ item?._source?.product_name }}
                        <span v-if="item?._source?.sku" class="smallsearchtext">SKU:<b> {{ item?._source?.sku }} </b></span>
                        <span v-if="item?._source?.mpn" class="smallsearchtext">MPN:<b> {{ item?._source?.mpn }} </b></span>
                        <span v-if="defaultSideBarMenu !== 'c'" class="smallsearchtext">{{ 'Org:'+item?._source?.ad_org_id }} </span></div>
                    </div>
                  </div>
                </div>
                <div class="column is-one-quarter">
                  <div class="list"> <!--<div class="list sizing">-->
                    <!--<div class="listItem active textAlign-center">
                      <strong class="fw-bold fg-hexfff">Sales/Purchase Orders</strong>
                    </div>-->
                    <div class="listHeader">
                      <strong class="fw-bold">Aufträge</strong>
                    </div>
                    <div class="listMenu">
                      <div v-for="item in orders" class="listItem" @click="goTo((item._source.isSOTrx ? '/sales/orders/' : '/sales/orders/')+item._source.c_order_id+'/edit', (item._source.issotrx ? 'Edit Sales Order' : 'Edit Purchase Order'))">{{ item?._source?.documentno }} </div>
                    </div>
                  </div>
                </div>
                <div class="column is-one-quarter">
                  <div class="list">
                    <div class="listHeader">
                      <strong class="fw-bold">Rechnungen</strong>
                    </div>
                    <div class="listMenu">
                      <div v-for="item in invoices" class="listItem" @click="goTo('/procurements/invoices/'+item._source.c_invoice_id, 'Edit Invoice')">{{ item?._source?.documentno }} </div>
                    </div>
                  </div>
                </div>
<!--                <div class="column is-one-quarter">-->
<!--                  <div class="list">-->
<!--                    <div class="listHeader">-->
<!--                      <strong class="fw-bold">Lieferscheine</strong>-->
<!--                    </div>-->
<!--                    <div class="listMenu">-->
<!--                      <div v-for="item in shipments" class="listItem" @click="goTo('/sales/shipments/'+item._source.m_inout_id+'/edit', 'Edit Shipment')">{{ item?._source?.documentno }} </div>-->
<!--                    </div>-->
<!--                  </div>-->
<!--                </div>-->
              </div>
            </div>

<!--            <div class="mt-0">-->
<!--              <div class="columns is-desktop">-->
<!--&lt;!&ndash;                <div class="column is-one-quarter">&ndash;&gt;-->
<!--&lt;!&ndash;                  <div class="list">&ndash;&gt;-->
<!--&lt;!&ndash;                    <div class="listHeader">&ndash;&gt;-->
<!--&lt;!&ndash;                      <strong class="fw-bold">Tickets</strong>&ndash;&gt;-->
<!--&lt;!&ndash;                    </div>&ndash;&gt;-->
<!--&lt;!&ndash;                    <div class="listMenu">&ndash;&gt;-->
<!--&lt;!&ndash;                      <div v-for="item in requests" class="listItem" @click="goTo('/requests/requests/'+item._source.r_request_id+'/edit', 'Edit Request')">{{ item?._source?.documentno }} </div>&ndash;&gt;-->
<!--&lt;!&ndash;                    </div>&ndash;&gt;-->
<!--&lt;!&ndash;                  </div>&ndash;&gt;-->
<!--&lt;!&ndash;                </div>&ndash;&gt;-->
<!--&lt;!&ndash;                <div class="column is-one-quarter">&ndash;&gt;-->
<!--&lt;!&ndash;                  <div class="list">&ndash;&gt;-->
<!--&lt;!&ndash;                    <div class="listHeader">&ndash;&gt;-->
<!--&lt;!&ndash;                      <strong class="fw-bold">Kontakte</strong>&ndash;&gt;-->
<!--&lt;!&ndash;                    </div>&ndash;&gt;-->
<!--&lt;!&ndash;                    <div class="listMenu">&ndash;&gt;-->
<!--&lt;!&ndash;                      <div v-for="item in users" class="listItem" @click="goTo('/edit/user-'+item._source.ad_user_id, 'Edit Shipment')">{{ item?._source?.name }} </div>&ndash;&gt;-->
<!--&lt;!&ndash;                    </div>&ndash;&gt;-->
<!--&lt;!&ndash;                  </div>&ndash;&gt;-->
<!--&lt;!&ndash;                </div>&ndash;&gt;-->


<!--              </div>-->
<!--            </div>-->
          </div>
        </div>
        <!--<div class="modalFooter">
          <div></div>
          <div class="d-flex gap-10px">
            <button type="button" class="button" @click="closeSearchModal">Close</button>
          </div>
        </div>-->
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal.active .modalDialog {
  padding: 0;
}
.modalContent {
  background: white;
}
.listItem {
  border-width: 1px;
}
.listMenu {
  max-height: 280px;
}

@media (min-width: 1024px) {
  .modalPrintPreview .modalContent {
    width: 90%;
  }
  .modalPrintPreview .modalContent {
    width: 90%;
    min-height: 64%;
  }
}

.smallsearchtext {
  font-size: 9px;
  color: grey;
  padding-left: 3px;
  border: 1px solid grey;
  border-radius: 3px;
  padding: 2px 2px 0px 2px;
  margin-left: 3px;
}

.mt-0 {
  min-height: 320px;
}
.smallsearchtitle {
  font-size: 10px;
  color: grey;
}

.listItem {
  font-size: 11px;
  padding: 2px;
}
</style>