<script setup>
  import Shepherd from 'shepherd.js'
  import { withQuery } from 'ufo'
  import { useConfigStore } from '@core/stores/config'

  defineOptions({
    // 👉 Is App Search Bar Visible
    inheritAttrs: false,
  })

  const { width: windowWidth } = useWindowSize();

  const configStore = useConfigStore()
  const isAppSearchBarVisible = ref(false)

  const searchQuery = ref('')
  const router = useRouter()
  const searchResult = ref([])
  const totalResults = ref(0)

  const userData = useCookie('userData').value

  const fetchResults = async () => {

    if (searchQuery.value.length < 2) {
      return
    }

    try {
      const res = await $api('/users/search', {
        method: 'GET',
        query: {
          q: searchQuery.value,
          userID: userData ? userData.id : null
        }
      })

      if (!res) return

      console.log('search result:', res)

      searchResult.value = res.data
      totalResults.value = res.totalResults
    } catch (error) {
      console.error('Error fetching search results:', error, error.response)
    }
  }

  watch(searchQuery, fetchResults)

  const redirectToSuggestedOrSearchedPage = selected => {

    if (!selected) return

    console.log('selected:', selected)


    router.push(selected.url)
    isAppSearchBarVisible.value = false
    searchQuery.value = ''
  }

  const LazyAppBarSearch = defineAsyncComponent(() => import('@core/components/AppBarSearch.vue'))

  const isMobile = ref(false)

  isMobile.value = windowWidth.value < 768

  watch(windowWidth, () => {
    isMobile.value = windowWidth.value < 768
  })

</script>

<template>
  <!-- 👉 App Bar Search -->
  <LazyAppBarSearch v-model:isDialogVisible="isAppSearchBarVisible" :search-results="searchResult"
    @search="searchQuery = $event">

    <!-- search result -->
    <template #searchResult="{ item }">

      <VListItem v-for="resultado in searchResult" :key="resultado.nome" link
        @click="redirectToSuggestedOrSearchedPage(resultado)">

        <template #prepend>

          <VAvatar size="60" :color="!resultado.foto ? 'primary' : undefined"
            :variant="!resultado.foto ? 'tonal' : undefined">
            <VImg v-if="resultado.foto" :src="resultado.foto" cover />
            <VIcon v-else icon="tabler-user" size="40" />
          </VAvatar>

        </template>

        <template #append v-if="!isMobile">
          <VBtn @click="redirectToSuggestedOrSearchedPage(resultado)" color="primary" text>
            Acessar
            <VIcon icon="tabler-arrow-right" class="ml-2" />
          </VBtn>
        </template>

        <VListItemTitle>

          <p class="mb-0 text-caption text-capitalize">
            {{ resultado.type }}
          </p>
          <p class="mb-0" :class="isMobile ? 'text-mobile-search' : 'text-primary font-weight-bold'">
            {{ resultado.nome }}
          </p>
          <p class="mb-0" style="font-size: 12px;line-height: 15px;">
            Ofertado por {{ resultado.empresa }}
          </p>
          <p class="mb-0 text-caption mt-2">
            <VIcon icon="tabler-map-pin" />
            {{ resultado.cidade + '/' + resultado.estado }}

            <VChip v-if="resultado.distance" color="primary" class="ml-1" label
              style="font-size: 14px; width: fit-content !important;">
              {{ resultado.distance.replace(' ', '') }} de você
            </VChip>
          </p>

        </VListItemTitle>

      </VListItem>

    </template>
  </LazyAppBarSearch>

  <!--<div class="d-flex align-center cursor-pointer" v-bind="$attrs" style="user-select: none;"
    @click="isAppSearchBarVisible = !isAppSearchBarVisible" v-if="!isMobile">
    <IconBtn class="me-1" @click="Shepherd.activeTour?.cancel()">
      <VIcon size="26" :icon="!isAppSearchBarVisible ? 'tabler-search' : 'tabler-x'" color="white" />
    </IconBtn>

  </div>-->
</template>

<style lang="scss"
       scoped>
        @use "@styles/variables/_vuetify.scss";

        .meta-key {
          border: thin solid rgba(var(--v-border-color), var(--v-border-opacity));
          border-radius: 6px;
          block-size: 1.5625rem;
          line-height: 1.3125rem;
          padding-block: 0.125rem;
          padding-inline: 0.25rem;
        }

        .text-mobile-search {
          color: var(--color-akkiperto);
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      </style>
