<template>
  <div class="admin--field-list">
    <!-- 상단 검색/액션 영역 -->
    <div class="admin--search-box type2">
      <div class="admin--search--inner--box">
        <div class="admin--search-form">
          <select v-model="searchField" class="admin--form-select admin--search-select">
            <option value="">전체</option>
            <option value="field">분야</option>
            <option value="area">지역명</option>
            <option value="name">선상명</option>
          </select>
          <input
            v-model="searchQuery"
            type="text"
            placeholder="검색어 입력"
            @keyup.enter="onSearch"
            class="admin--form-input admin--search-input"
          />
          <select v-model="filterPartnership" @change="onSearch" class="admin--form-select admin--search-select">
            <option value="">전체</option>
            <option value="Y">제휴</option>
            <option value="N">비제휴</option>
          </select>
          <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>
          <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--search--inner--box">
        <div class="admin--search-form">
          <DatePicker v-model="startDate" placeholder="📅 YYYY-MM-DD" />
          <span class="admin--date-separator">-</span>
          <DatePicker v-model="endDate" placeholder="📅 YYYY-MM-DD" />
          <div class="admin--quick-range">
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('today')">오늘</button>
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('7d')">7일</button>
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('15d')">15일</button>
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('1m')">1개월</button>
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('3m')">3개월</button>
            <button type="button" class="admin--btn-small admin--btn-small-secondary range--btn" @click="setRange('1y')">1년</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 테이블 -->
    <div class="admin--table-wrapper">
      <table class="admin--table fishing--table">
        <thead>
          <tr>
            <th style="width: 80px;">번호</th>
            <th style="width: 140px;">분야</th>
            <th style="width: 140px;">지역명</th>
            <th>선상명</th>
            <th style="width: 100px;">제휴업체</th>
            <th style="width: 100px;">상태</th>
            <th style="width: 120px;">등록일</th>
            <th style="width: 120px;">관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="8" class="admin--table-loading">데이터를 불러오는 중...</td>
          </tr>
          <tr v-else-if="!onboards || onboards.length === 0">
            <td colspan="8" class="admin--table-empty">등록된 선상이 없습니다.</td>
          </tr>
          <tr
            v-else
            v-for="(item, index) in onboards"
            :key="item.id"
            class="admin--table-row-clickable"
            @click="goToDetail(item.id)"
          >
            <td class="date">{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td>{{ item.field_name || "-" }}</td>
            <td>{{ item.area_name || "-" }}</td>
            <td class="admin--table-title">{{ item.name }}</td>
            <td>
              <span :class="['admin--badge', item.partnership_YN === 'Y' ? 'admin--badge-active' : 'admin--badge-ended']">
                {{ item.partnership_YN === "Y" ? "제휴" : "비제휴" }}
              </span>
            </td>
            <td>
              <span :class="['admin--badge', getStatusBadgeClass(item.status_YN)]">
                {{ getStatusLabel(item.status_YN) }}
              </span>
            </td>
            <td class="date">{{ formatDate(item.created_at) }}</td>
            <td>
              <div class="admin--table-actions">
                <button class="admin--btn-small admin--btn-blue" @click.stop="goToEdit(item.id)">
                  수정
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 페이지네이션 -->
    <div v-if="totalPages > 1" class="admin--pagination">
      <button
        v-if="totalPages > 2"
        class="admin--pagination-btn"
        :disabled="currentPage === 1"
        @click="changePage(1)"
        title="처음"
      >
        ◀◀
      </button>
      <button
        class="admin--pagination-btn"
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
        title="이전"
      >
        ◀
      </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)"
        title="다음"
      >
        ▶
      </button>
      <button
        v-if="totalPages > 2"
        class="admin--pagination-btn"
        :disabled="currentPage === totalPages"
        @click="changePage(totalPages)"
        title="끝"
      >
        ▶▶
      </button>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from "vue";
  import { useRouter } from "vue-router";
  import DatePicker from "~/components/admin/DatePicker.vue";

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

  const router = useRouter();
  const { get } = useApi();

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

  const searchField = ref("");      // '', field, area, name
  const searchQuery = ref("");
  const filterPartnership = ref(""); // '', Y, N
  const filterStatus = ref("");      // '', Y, N
  const startDate = ref("");         // YYYY-MM-DD
  const endDate = ref("");           // YYYY-MM-DD

  // YYYY-MM-DD 포맷터
  const toYMD = (d) => {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
  };

  // 빠른 기간 선택 (오늘 기준)
  const setRange = (kind) => {
    const today = new Date();
    const end = toYMD(today);
    const startDt = new Date();
    switch (kind) {
      case "today":
        break;
      case "7d":
        startDt.setDate(startDt.getDate() - 7);
        break;
      case "15d":
        startDt.setDate(startDt.getDate() - 15);
        break;
      case "1m":
        startDt.setMonth(startDt.getMonth() - 1);
        break;
      case "3m":
        startDt.setMonth(startDt.getMonth() - 3);
        break;
      case "1y":
        startDt.setFullYear(startDt.getFullYear() - 1);
        break;
    }
    startDate.value = toYMD(startDt);
    endDate.value = end;
    onSearch();
  };

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

    const params = {
      page: currentPage.value,
      per_page: perPage.value,
    };
    if (searchQuery.value) {
      params.search = searchQuery.value;
      if (searchField.value) params.search_field = searchField.value;
    }
    if (filterPartnership.value) params.partnership = filterPartnership.value;
    if (filterStatus.value) params.status = filterStatus.value;
    if (startDate.value) params.start_date = startDate.value;
    if (endDate.value) params.end_date = endDate.value;

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

    if (error) {
      console.error("[OnboardList] 목록 로드 실패:", error);
      onboards.value = [];
      totalCount.value = 0;
      totalPages.value = 0;
    } else if (data?.success && data?.data) {
      onboards.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;
    loadOnboards();
  };

  // 검색 초기화
  const resetSearch = () => {
    searchField.value = "";
    searchQuery.value = "";
    filterPartnership.value = "";
    filterStatus.value = "";
    startDate.value = "";
    endDate.value = "";
    currentPage.value = 1;
    loadOnboards();
  };

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

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

  // 상태 라벨 / 뱃지 클래스
  const getStatusLabel = (status) => (status === "Y" ? "사용중" : "미사용");
  const getStatusBadgeClass = (status) =>
    status === "Y" ? "admin--badge-active" : "admin--badge-ended";

  // 날짜 포맷
  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(() => {
    loadOnboards();
  });
</script>