<template>
  <div class="admin--popup-list">
    <!-- 검색 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <select v-model="searchType" class="admin--form-select admin--search-select">
          <option value="title">제목</option>
          <option value="status">상태</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="!popups || popups.length === 0">
            <td colspan="7" class="admin--table-empty">
              등록된 팝업이 없습니다.
            </td>
          </tr>
          <tr v-else v-for="(popup, index) in popups" :key="popup.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td>
              <span class="admin--badge" :class="`admin--badge-${popup.type}`">
                {{ popup.type === 'html' ? 'HTML' : '단일페이지' }}
              </span>
            </td>
            <td class="admin--table-title">{{ popup.title }}</td>
            <td>{{ formatDateTime(popup.start_date, popup.start_time) }}</td>
            <td>{{ formatDateTime(popup.end_date, popup.end_time) }}</td>
            <td>
              <span class="admin--badge" :class="getStatusClass(popup)">
                {{ getStatusText(popup) }}
              </span>
            </td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(popup.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="handleDelete(popup.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(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
        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'

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

const router = useRouter()
const { get, del } = useApi()
const popups = ref([])
const searchType = ref('title')
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 loadPopups = 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('/basic/popup', { params })

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

  // API 응답: { success: true, data: { items, total, page }, message }
  if (data?.success && data?.data) {
    popups.value = data.data.items || []
    totalCount.value = data.data.total || 0
    totalPages.value = Math.ceil(totalCount.value / perPage.value)
    console.log('[Popup List] 로드 성공:', {
      items: popups.value.length,
      total: totalCount.value,
      pages: totalPages.value
    })
  } else {
    console.log('[Popup List] 데이터 없음 또는 에러')
  }
}

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

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

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

// 등록 페이지로 이동
const goToCreate = () => {
  router.push('/site-manager/basic/popup/create')
}

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

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

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

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

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

// 날짜 포맷
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`
}

// 날짜+시간 포맷 ("HH:MM:SS" → "오전/오후 H:MM")
const formatDateTime = (dateString, timeString) => {
  const d = formatDate(dateString)
  if (!timeString) return d
  const [hStr, mStr] = String(timeString).split(':')
  let h = Number(hStr)
  const m = Number(mStr || 0)
  if (isNaN(h)) return d
  const period = h >= 12 ? '오후' : '오전'
  const hour12 = h % 12 === 0 ? 12 : h % 12
  return `${d} ${period} ${hour12}:${String(m).padStart(2, '0')}`
}

// 팝업 시작/종료 Date 계산 (시간 null 처리 포함)
const buildStart = (popup) => new Date(`${popup.start_date}T${popup.start_time || '00:00:00'}`)
const buildEnd = (popup) => new Date(`${popup.end_date}T${popup.end_time || '23:59:59'}`)

// 상태 클래스
const getStatusClass = (popup) => {
  const now = new Date()
  const start = buildStart(popup)
  const end = buildEnd(popup)

  if (now < start) return 'admin--badge-scheduled'
  if (now > end) return 'admin--badge-ended'
  return 'admin--badge-active'
}

// 상태 텍스트
const getStatusText = (popup) => {
  const now = new Date()
  const start = buildStart(popup)
  const end = buildEnd(popup)

  if (now < start) return '예정'
  if (now > end) return '종료'
  return '진행중'
}

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