<template>
  <div class="admin--advisor-list">
    <!-- 검색 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <select v-model="searchType" class="admin--form-select admin--search-select">
          <option value="all">전체</option>
          <option value="name">이름</option>
          <option value="service_center">서비스센터</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>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="!advisors || advisors.length === 0">
            <td colspan="7" class="admin--table-empty">등록된 어드바이저가 없습니다.</td>
          </tr>
          <tr v-else v-for="(advisor, index) in advisors" :key="advisor.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td>
              <div class="admin--table-photo">
                <img
                  v-if="advisor.photo_url"
                  :src="getImageUrl(advisor.photo_url)"
                  :alt="advisor.name"
                />
                <div v-else class="admin--table-photo-empty">사진없음</div>
              </div>
            </td>
            <td>{{ advisor.service_center_name }}</td>
            <td class="admin--table-title">{{ advisor.name }}</td>
            <td>{{ advisor.main_phone }}</td>
            <td>{{ advisor.direct_phone }}</td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(advisor.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="handleDelete(advisor.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 { getImageUrl } = useImage();
  const advisors = ref([]);
  const searchType = ref("all");
  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 loadAdvisors = 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("/staff/advisor", params);

    console.log("[Advisor] API 응답:", { data, error });

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

  const handleSearch = () => {
    currentPage.value = 1;
    loadAdvisors();
  };

  const handleReset = () => {
    searchType.value = "all";
    searchKeyword.value = "";
    currentPage.value = 1;
    loadAdvisors();
  };

  const changePage = (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    loadAdvisors();
  };

  const goToCreate = () => {
    router.push("/admin/staff/advisor/create");
  };

  const goToEdit = (id) => {
    router.push(`/admin/staff/advisor/edit/${id}`);
  };

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

    const { error } = await del(`/staff/advisor/${id}`);

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

  onMounted(() => {
    loadAdvisors();
  });
</script>

<style scoped>
  /* 검색 영역 input/select 스타일 통일 */
  .admin--search-box .admin--form-input,
  .admin--search-box .admin--search-input,
  .admin--search-box .admin--form-select,
  .admin--search-box .admin--search-select {
    border: 1px solid var(--admin-border-color) !important;
    border-radius: 4px;
    height: 33px !important;
    padding: 6px 14px !important;
    font-size: 13px !important;
  }
</style>
