<template>
  <h3 class="ptc-title">Choose a store</h3>
  <div class="ptc-block">
    <div class="ptc-inner-md pr">
      <form class="search-wrap" action="">
        <input
          type="search"
          class="search-input ptc-input"
          placeholder="Search by zip code"
          @input="autocomplete"
        />
        <div role="button" class="search-btn ptc-button"></div>
      </form>
      <div v-if="showSuggestions" class="search-suggestions">
        <div class="suggestion">PTC Browns Plains Kiosk</div>
        <div class="suggestion">PTC Browns Plains Kiosk</div>
      </div>
      <div class="shop-wrap">
        <div class="tip">Nearby shops</div>
        <InfiniteList
          class="shop-list-wrap"
          :loading="loading"
          :has-more="hasMore"
          scroll-target=".shop-list-wrap"
          @loadmore="fetchData"
        >
          <ul class="shop-list">
            <li
              v-for="(item, index) of list"
              :key="index"
              class="shop-item border-bottom"
              @click="state.step++"
            >
              <div class="shop-name">
                <span>{{ item.name }}</span>
                <span>3.5KM</span>
              </div>
              <div class="shop-address">
                {{ item.shop_detail }},{{ item.address }}
              </div>
              <div class="shop-mark" :class="{ danger: !item.can_appointment }">
                <i class="icon"></i
                >{{
                  item.can_appointment
                    ? item.can_appointment_day
                    : 'No appointments available for the next 7 days'
                }}
              </div>
            </li>
          </ul>
        </InfiniteList>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { state } from './store'
import { getShopList } from '@/service/repair'
import getLocation from '@/utils/getLocation'
import InfiniteList from '@/components/infinite-list/index.vue'

const showSuggestions = ref(false)
const loading = ref(false)
const hasMore = ref(true)
const list = ref<any[]>()
let pageNo = 1
let coords: any = null

async function fetchData() {
  loading.value = true
  try {
    if (!list.value) {
      list.value = []
      const res = await getLocation({ timeout: 2000 })
      coords = res?.coords
    }
    const { results, pageBean } = await getShopList({})
    list.value.push(...results)
    pageNo++
    hasMore.value = list.value.length === pageBean.totalCount
  } catch {}
  loading.value = false
}

function autocomplete(e: any) {
  showSuggestions.value = e.target.value.length > 0
}
</script>
