<template>
  <div>
    <div class="page-header">
      <h2>${Name}</h2>
      <router-link to="/${name}/new" class="btn btn-primary">Add ${Name}</router-link>
    </div>

    <div class="filters">
      <input
        v-model="search"
        type="text"
        class="form-control"
        placeholder="Search..."
        @input="debouncedSearch"
      />
    </div>

    <div class="card">
      <div v-if="loading" class="loading">Loading...</div>

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Asset Tag</th>
                <th>Name</th>
                <th>Example Field</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in items" :key="item.assetid">
                <td>{{ item.assetnumber || '-' }}</td>
                <td>{{ item.name || '-' }}</td>
                <td>{{ item.examplefield || '-' }}</td>
                <td class="actions">
                  <router-link
                    :to="`/${name}/${item.assetid}`"
                    class="btn btn-secondary btn-sm"
                  >
                    View
                  </router-link>
                </td>
              </tr>
              <tr v-if="items.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No ${name} records found
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <PaginationBar
          :page="page"
          :totalPages="totalPages"
          :perPage="perPage"
          @update:page="goToPage"
          @update:perPage="changePerPage"
        />
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../../api'
import PaginationBar from '../../components/PaginationBar.vue'

// local api client. move into src/api/index.js (see
// plugins/${name}/frontend-api-snippet.js) then swap for:
//   import { ${name}Api } from '../../api'
const ${name}Api = {
  list(params = {}) { return api.get('/${name}', { params }) },
  get(itemId) { return api.get(`/${name}/${itemId}`) },
  create(data) { return api.post('/${name}', data) },
  update(itemId, data) { return api.put(`/${name}/${itemId}`, data) },
  remove(itemId) { return api.delete(`/${name}/${itemId}`) }
}

const items = ref([])
const loading = ref(true)
const search = ref('')
const page = ref(1)
const totalPages = ref(1)
const perPage = ref(25)
let searchTimeout = null

onMounted(loadItems)

async function loadItems() {
  loading.value = true
  try {
    const params = { page: page.value, perpage: perPage.value }
    if (search.value) params.search = search.value
    const response = await ${name}Api.list(params)
    items.value = response.data.data || []
    totalPages.value = response.data.meta?.pagination?.totalpages || 1
  } catch (error) {
    console.error('Error loading ${name}:', error)
  } finally {
    loading.value = false
  }
}

function debouncedSearch() {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    page.value = 1
    loadItems()
  }, 300)
}

function goToPage(target) {
  if (target >= 1 && target <= totalPages.value) {
    page.value = target
    loadItems()
  }
}

function changePerPage(newPerPage) {
  perPage.value = newPerPage
  page.value = 1
  loadItems()
}
</script>

<style scoped>
.filters {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.filters .form-control {
  flex: 1;
  min-width: 150px;
}
</style>
