<template>
  <div class="admin--branch-list">
    <!-- 상단 버튼 -->
    <div class="admin--search-box">
      <div class="admin--search-form"></div>
      <div class="admin--search-actions">
        <button class="admin--btn admin--btn-primary" @click="goToCreate">
          + 지점 등록
        </button>
      </div>
    </div>

    <!-- 테이블 -->
    <div class="admin--table-wrapper">
      <table class="admin--table">
        <thead>
          <tr>
            <th>NO</th>
            <th>지점명</th>
            <th>대표번호</th>
            <th>주소</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="5" class="admin--table-loading">
              데이터를 불러오는 중...
            </td>
          </tr>
          <tr v-else-if="!branches || branches.length === 0">
            <td colspan="5" class="admin--table-empty">
              등록된 지점이 없습니다.
            </td>
          </tr>
          <tr v-else v-for="(branch, index) in branches" :key="branch.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td class="admin--table-title">{{ branch.name }}</td>
            <td>{{ branch.main_phone }}</td>
            <td>{{ branch.address }}</td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(branch.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="deleteBranch(branch.id)"
                >
                  삭제
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 페이지네이션 -->
    <div v-if="totalPages > 1" class="admin--pagination">
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
      >
        이전
      </button>
      <button
        v-for="page in visiblePages"
        :key="page"
        class="admin--pagination-btn"
        :class="{ 'is-active': page === currentPage }"
        @click="changePage(page)"
      >
        {{ page }}
      </button>
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
      >
        다음
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

definePageMeta({
  layout: 'admin',
  middleware: ['auth']
})

const router = useRouter()
const { get, del } = useApi()

const isLoading = ref(false)
const branches = ref([])
const currentPage = ref(1)
const perPage = ref(10)
const totalCount = ref(0)
const totalPages = ref(0)

// 보이는 페이지 번호 계산
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  let end = Math.min(totalPages.value, start + maxVisible - 1)

  if (end - start < maxVisible - 1) {
    start = Math.max(1, end - maxVisible + 1)
  }

  for (let i = start; i <= end; i++) {
    pages.push(i)
  }

  return pages
})

// 데이터 로드
const loadBranches = async () => {
  isLoading.value = true

  const params = {
    page: currentPage.value,
    per_page: perPage.value
  }

  const { data, error } = await get('/branch/list', params)

  console.log('[BranchList] API 응답:', { data, error })

  // API 응답: { success: true, data: { items, total }, message }
  if (data?.success && data?.data) {
    branches.value = data.data.items || []
    totalCount.value = data.data.total || 0
    totalPages.value = Math.ceil(totalCount.value / perPage.value)
    console.log('[BranchList] 로드 성공:', branches.value.length)
  }

  isLoading.value = false
}

// 페이지 변경
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  loadBranches()
}

// 지점 등록 페이지로 이동
const goToCreate = () => {
  router.push('/admin/branch/create')
}

// 지점 수정 페이지로 이동
const goToEdit = (id) => {
  router.push(`/admin/branch/edit/${id}`)
}

// 지점 삭제
const deleteBranch = async (id) => {
  if (!confirm('정말 삭제하시겠습니까?')) return

  const { data, error } = await del(`/branch/${id}`)

  if (error || !data?.success) {
    alert(error?.message || data?.message || '삭제에 실패했습니다.')
  } else {
    alert(data.message || '지점이 삭제되었습니다.')
    loadBranches()
  }
}

onMounted(() => {
  loadBranches()
})
</script>

<style scoped>
.admin--search-actions .admin--btn-primary {
  background: var(--admin-accent-primary);
  color: white;
  border-color: var(--admin-accent-primary);
  font-weight: 500;
  padding: 8px 18px;
  font-size: 13px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.admin--search-actions .admin--btn-primary:hover {
  background: var(--admin-accent-hover);
  border-color: var(--admin-accent-hover);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
