<template>
  <div class="admin--field-list">
    <!-- 상단 검색/액션 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <!-- <select v-model="filterStatus" @change="onSearch" class="admin--form-select admin--search-select">
          <option value="">전체 상태</option>
          <option value="Y">사용중</option>
          <option value="N">미사용</option>
        </select> -->
        <input
          v-model="searchQuery"
          type="text"
          placeholder="지역명으로 검색"
          @keyup.enter="onSearch"
          class="admin--form-input admin--search-input"
        />
        <button @click="onSearch" class="admin--btn-small admin--btn-small-primary">검색</button>
        <button @click="resetSearch" class="admin--btn-small admin--btn-small-secondary">초기화</button>
      </div>
      <div class="admin--search-actions">
        <button class="admin--btn-add" @click="goToCreate">+ 새 지역 추가</button>
      </div>
    </div>

    <!-- 테이블 -->
    <div class="admin--table-wrapper">
      <table class="admin--table">
        <thead>
          <tr>
            <th style="width: 80px;">번호</th>
            <th style="width: 60%;">지역</th>
            <th>등록일</th>
            <th style="width: 120px;">관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="6" class="admin--table-loading">데이터를 불러오는 중...</td>
          </tr>
          <tr v-else-if="!fields || fields.length === 0">
            <td colspan="6" class="admin--table-empty">등록된 지역이 없습니다.</td>
          </tr>
          <tr
            v-else
            v-for="(field, index) in fields"
            :key="field.id"
            class="admin--table-row-clickable"
            @click="goToDetail(field.id)"
          >
            <td class="date">{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td class="admin--table-title">{{ field.name }}</td>
            <td class="date">{{ formatDate(field.created_at) }}</td>
            <td>
              <div class="admin--table-actions">
                <button class="admin--btn-small admin--btn-blue" @click.stop="goToEdit(field.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 } = useApi();

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

  const searchQuery = ref("");

  // 보이는 페이지 번호 계산
  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 loadFields = async () => {
    isLoading.value = true;

    const params = {
      page: currentPage.value,
      per_page: perPage.value,
    };
    if (searchQuery.value) params.search = searchQuery.value;

    const { data, error } = await get("/area/list", { params });

    if (error) {
      console.error("[AreaList] 목록 로드 실패:", error);
      fields.value = [];
      totalCount.value = 0;
      totalPages.value = 0;
    } else if (data?.success && data?.data) {
      fields.value = data.data.items || [];
      totalCount.value = data.data.total || 0;
      totalPages.value = data.data.total_pages || 0;
    }

    isLoading.value = false;
  };

  // 검색
  const onSearch = () => {
    currentPage.value = 1;
    loadFields();
  };

  // 검색 초기화
  const resetSearch = () => {
    searchQuery.value = "";
    currentPage.value = 1;
    loadFields();
  };

  // 페이지 변경
  const changePage = (page) => {
    if (page < 1 || page > totalPages.value) return;
    currentPage.value = page;
    loadFields();
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  // 이동
  const goToCreate = () => router.push("/site-manager/area/create");
  const goToDetail = (id) => router.push(`/site-manager/area/detail/${id}`);
  const goToEdit = (id) => router.push(`/site-manager/area/edit/${id}`);

  // 날짜 포맷
  const formatDate = (dateString) => {
    if (!dateString) return "-";
    const date = new Date(dateString.replace(" ", "T"));
    if (isNaN(date.getTime())) return dateString;
    return date.toLocaleDateString("ko-KR", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    });
  };

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