<template>
  <div class="search-result">
    <ClientOnly>
      <div
        v-if="latestSearches && latestSearches.length && searchValue.length <= 2"
        class="search-result__default"
      >
        <p class="search-result__default-title">{{ $t('search_recent_searches') }}</p>
        <SearchItem
          v-for="item in latestSearches"
          :key="`placeholder-search-last-${item}`"
          :item="item"
          is-default
          class="search-result__item"
          prefix="search"
        />
      </div>
    </ClientOnly>
    <div
      v-if="relatedSearch && relatedSearch.length && searchValue.length <= 2"
      class="search-result__default"
    >
      <p class="search-result__default-title">{{ $t('popular_searches') }}</p>
      <SearchItem
        v-for="item in relatedSearchesItems?.slice(0, 10)"
        :key="`placeholder-search-videos-${item}`"
        :item="item"
        is-default
        class="search-result__item"
        prefix="search"
      />
    </div>
    <div
      v-if="topModels && searchValue.length <= 2"
      class="search-result__default"
    >
      <p class="search-result__default-title">{{ $t('trending_models') }}</p>
      <SearchItem
        v-for="item in topModels?.slice(0, 5)"
        :key="`placeholder-search-top-model-${item.title}`"
        :item="item"
        is-default
        class="search-result__item"
        prefix="models"
      />
    </div>

    <template v-else-if="result && Object.values(result).filter(item => item).length">
      <div class="search-result__buttons">
        <UiChips
          v-for="item in tabs"
          :key="`search-${item.title}`"
          :item="item"
          :active="activeTab === item.value"
          class="search-result__button"
          @click="onTabClick(item.value)"
        />
      </div>

      <div class="search-result__wrapper">
        <div
          v-if="result.searchPhrases && result.searchPhrases.length > 0 && (activeTab === 'searchPhrases' || !activeTab)"
          class="search-result__items"
        >
          <p class="search-result__subtitle">{{ $t('videos') }}</p>
          <SearchItem
            v-for="item in result.searchPhrases.map((subItem: string) => ({
              title: subItem,
              name: subItem,
            }))"
            :key="item.name"
            :item="item"
            simple
            prefix="search"
          />
        </div>

        <div
          v-if="result.categories && result.categories.length > 0 && (activeTab === 'categories' || !activeTab)"
          class="search-result__items"
        >
          <p class="search-result__subtitle">{{ $t('categories') }}</p>
          <SearchItem
            v-for="item in result.categories"
            :key="item.name"
            :item="item"
            simple
            prefix="categories"
          />
        </div>

        <div
          v-if="result.models && result.models.length > 0 && (activeTab === 'models' || !activeTab)"
          class="search-result__items"
        >
          <p class="search-result__subtitle">{{ $t('models') }}</p>
          <SearchItem
            v-for="item in result.models"
            :key="item.name"
            :item="item"
            prefix="models"
          />
        </div>
      </div>
    </template>

    <div
      v-else-if="status === 'pending'"
      class="search-result__loading _loading"
    />
    <p
      v-else
      class="search-result__empty"
    >
      {{ $t('no_results_found') }}
    </p>
  </div>
</template>

<script setup lang="ts">
import type { IModelCard } from '../../types';
import { AsyncData } from '../../runtime';
import { buildSearchTabs } from '../../utils/search-result/build-search-tabs';
import { SearchApiService } from '../../services/api/search.service';
import { ModelsApiService } from '../../services/api/models.service';

const searchValue = useState<string>('searchValue', () => '');

const [
  { data: result, status },
  { data: relatedSearch },
  { data: dataModels },
] = await Promise.all([
  useFetchMultiSuggest(SearchApiService.getMultiSuggest, 10, 10, 10),
  useFetchRelatedSearch(SearchApiService.getPhrases),
  useFetchTopModels(ModelsApiService.getTop, 8, AsyncData.TopModels, searchValue.value),
]);

const activeTab = ref('');

const topModels = computed(() => {
  return dataModels.value?.items?.map((item: IModelCard) => ({
    title: item.title,
    name: item.title,
    videosCount: item.videosCount,
  })) || [];
});

const tabs = computed(() => buildSearchTabs(result.value));

function onTabClick(value: string) {
  activeTab.value = value;
}

const relatedSearchesItems = computed(() => relatedSearch.value?.map(item => ({
  title: item,
  name: item,
})));

const latestSearchesRaw = ref<string[]>([]);

onMounted(() => {
  latestSearchesRaw.value = JSON.parse(localStorage.getItem('recentSearches') || '[]');
});

const latestSearches = computed(() =>
    latestSearchesRaw.value.map(item => ({
      title: item,
      name: item
    }))
);
</script>

<style lang="scss">
.search-result {
  max-height: 70vh;
  max-height: 70dvh;
  overflow: auto;
  scrollbar-width: thin;
  scrollbar-color: $search-result-scrollbar;
  color: $search-result-text--mobile;
  width: calc(100vw - calc(var(--container-padding-inline) * 2));
  border: 1px solid $search-result-border--mobile;
  border-radius: $radius;
  background-color: $search-result-bg--mobile;
  box-shadow: $search-result-shadow;

  @include to-br(sm) {
    position: fixed;
    left: var(--container-padding-inline);
    top: var(--header-height);
    z-index: $z-index-popup + 1;
  }

  @include from-br(sm) {
    max-height: 90vh;
    max-height: 90dvh;
    display: grid;
    width: $search-max-width;
    color: $search-result-text;
    border: 1px solid $search-result-border;
    border-radius: $radius;
    background-color: $search-result-bg;
    padding-bottom: 8px;
  }

  @include from-br(md) {
    width: $search-max-width-md;
  }
}

.search-result__default-title {
  @include font-sm;

  font-weight: 600;

  @include from-br(sm) {
    margin-bottom: 8px;
  }
}

.search-result__default {
  padding: 12px;

  @include to-br(sm) {
    row-gap: 8px;
  }
}

.search-result__default:not(:last-of-type) {
  border-bottom: 1px solid $search-result-border--mobile;

  @include from-br(sm) {
    border-bottom-color: $search-result-border;
  }
}

.search-result__default,
.search-result__wrapper {
  display: grid;
}

.search-result__wrapper {
  row-gap: 8px;
}

.search-result__buttons {
  display: flex;
  column-gap: 4px;
  padding: 8px;
  border-bottom: 1px solid $search-result-border;
  overflow: auto;
}

.search-result__buttons .search-result__button {
  text-transform: capitalize;
  height: 32px;
  font-weight: 700;
}

.search-result__items {
  display: grid;
  padding: 8px;
  align-items: center;

  @include to-br(sm) {
    row-gap: 8px;
  }
}

.search-result__subtitle {
  @include from-br(sm) {
    margin-bottom: 8px;
  }
}

.search-result__empty {
  padding: 8px;

  @include from-br(sm) {
    min-height: 10vh;
  }
}

.search-result__loading {
  height: 30vh;
}
</style>
