<script setup lang="ts">
import SearchSkeleton from './components/search-skeleton.vue'
import SearchTagCloud from './components/search-tag-cloud.vue'
import { useSearchStore } from '@/store'
import { appRecipeCategoryListGet } from '@/service'
import { decodeRouteQueryValue } from '@/utils/utils'

const { t } = useI18n()
const searchStore = useSearchStore()

const keyword = ref('')
function handleSearch() {
  nextTick(() => {
    if (!keyword.value) {
      return uni.showToast({
        title: t('common.prompt.please-enter-keyword-search'),
        icon: 'none',
      })
    }
    const kw = decodeRouteQueryValue(keyword.value)
    if (!kw) {
      return uni.showToast({
        title: t('common.prompt.please-enter-keyword-search'),
        icon: 'none',
      })
    }
    searchStore.setHistoryList(kw)
    uni.navigateTo({
      url: `/pages/search/result?keyword=${encodeURIComponent(kw)}`,
    })
    keyword.value = ''
  })
}

function goResultWithKeyword(k: string) {
  const kw = decodeRouteQueryValue(k)
  if (!kw) return
  searchStore.setHistoryList(kw)
  uni.navigateTo({
    url: `/pages/search/result?keyword=${encodeURIComponent(kw)}`,
  })
}

function handleHotSearch(item: Record<string, unknown>) {
  const name = String(item?.categoryName ?? '')
  goResultWithKeyword(name)
}

function onHistorySelect(tag: { text: string }) {
  goResultWithKeyword(tag.text)
}

function onHistoryRemove(index: number) {
  searchStore.historyList.splice(index, 1)
}

function onHistoryClear() {
  searchStore.clearHistory()
}

const loading = ref(true)
onMounted(() => {
  loading.value = true
  getHotSearchList()
})

const hotSearchList = ref<Record<string, unknown>[]>([])
function getHotSearchList() {
  appRecipeCategoryListGet({})
    .then((res) => {
      hotSearchList.value = (res.data as Record<string, unknown>[]) || []
    })
    .finally(() => {
      loading.value = false
    })
}

const historyTags = computed(() =>
  searchStore.historyList.map((h, i) => ({
    key: `${h.time}-${i}`,
    text: decodeRouteQueryValue(h.text),
    removable: true,
  })),
)

const hotTags = computed(() =>
  hotSearchList.value.map((item, i) => ({
    key: String(item.id ?? `hot-${i}`),
    text: String(item.categoryName ?? ''),
    hot: i < 3,
  })),
)

function onHotSelect(tag: { key: string | number }) {
  const idx = hotTags.value.findIndex((x) => x.key === tag.key)
  const raw = idx >= 0 ? hotSearchList.value[idx] : null
  if (raw) handleHotSearch(raw)
}
</script>

<template>
  <view class="search-page">
    <view
      class="animate-in fade-in animate-ease-out animate-duration-300"
      v-show="loading"
    >
      <search-skeleton />
    </view>
    <view
      class="animate-in fade-in animate-ease-in animate-duration-300 search-page__content"
      v-show="!loading"
    >
      <header-search
        v-model="keyword"
        focus
        trailing-cart
        class="search-page__header"
        :placeholder="t('components.search.placeholder')"
        @search="handleSearch"
      />
      <view class="search-page__body">
        <search-tag-cloud
          v-if="historyTags.length > 0"
          :title="t('pages.search.recently')"
          :tags="historyTags"
          show-clear
          @select="onHistorySelect"
          @remove="onHistoryRemove"
          @clear="onHistoryClear"
        />
        <search-tag-cloud
          v-if="hotTags.length > 0"
          :title="t('pages.search.hot-title')"
          :tags="hotTags"
          @select="onHotSelect"
        />
      </view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f7f8fa;
}
</style>

<style scoped lang="scss">
.search-page {
  min-height: 100vh;
  background: #f7f8fa;
}
.search-page__content {
  min-height: 100vh;
  background: #f7f8fa;
}
.search-page__body {
  padding-bottom: 48rpx;
}
</style>
