<template>
  <div class="admin--manager-list">
    <!-- 검색 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <select v-model="searchType" class="admin--form-select admin--search-select">
          <option value="branch_name">지점명</option>
          <option value="name">이름</option>
          <option value="user_id">아이디</option>
          <option value="email">이메일</option>
        </select>
        <input
          v-model="searchKeyword"
          type="text"
          class="admin--form-input admin--search-input"
          placeholder="검색어를 입력하세요"
          @keyup.enter="handleSearch"
        >
        <button class="admin--btn-small admin--btn-small-primary" @click="handleSearch">
          검색
        </button>
        <button class="admin--btn-small admin--btn-small-secondary" @click="handleReset">
          초기화
        </button>
      </div>
      <div class="admin--search-actions">
        <button class="admin--btn-small admin--btn-small-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>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="!managers || managers.length === 0">
            <td colspan="6" class="admin--table-empty">
              등록된 지점장이 없습니다.
            </td>
          </tr>
          <tr v-else v-for="(manager, index) in managers" :key="manager.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td>{{ manager.branch_name }}</td>
            <td class="admin--table-title">{{ manager.name }}</td>
            <td>{{ manager.username }}</td>
            <td>{{ manager.email }}</td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(manager.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="handleDelete(manager.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 managers = ref([])
const searchType = ref('branch_name')
const searchKeyword = 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 loadManagers = async () => {
  const params = {
    page: currentPage.value,
    per_page: perPage.value
  }

  if (searchKeyword.value) {
    params.search_type = searchType.value
    params.search_keyword = searchKeyword.value
  }

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

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

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

// 검색
const handleSearch = () => {
  currentPage.value = 1
  loadManagers()
}

// 초기화
const handleReset = () => {
  searchType.value = 'branch_name'
  searchKeyword.value = ''
  currentPage.value = 1
  loadManagers()
}

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

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

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

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

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

  if (error) {
    alert('삭제에 실패했습니다.')
  } else {
    alert('삭제되었습니다.')
    loadManagers()
  }
}

onMounted(() => {
  loadManagers()
})
</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>
