<template>
  <div class="admin--brochure-list">
    <!-- 검색 영역 -->
    <div class="admin--search-box">
      <div class="admin--search-form">
        <input
          v-model="searchKeyword"
          type="text"
          class="admin--form-input admin--search-input"
          placeholder="신청자명으로 검색"
          @keyup.enter="handleSearch"
        >
        <button class="admin--btn admin--btn-primary" @click="handleSearch">
          검색
        </button>
        <button class="admin--btn admin--btn-secondary" @click="handleReset">
          초기화
        </button>
      </div>
      <div class="admin--search-actions">
        <button class="admin--btn admin--btn-secondary" @click="handleExcelDownload">
          엑셀 다운로드
        </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>
            <th>상태</th>
            <th>관리</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="9" class="admin--table-loading">
              데이터를 불러오는 중...
            </td>
          </tr>
          <tr v-else-if="!brochures || brochures.length === 0">
            <td colspan="9" class="admin--table-empty">
              브로셔 요청이 없습니다.
            </td>
          </tr>
          <tr v-else v-for="(brochure, index) in brochures" :key="brochure.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td class="admin--table-title">{{ brochure.name }}</td>
            <td>{{ brochure.branch_name }}</td>
            <td>{{ brochure.car_model }}</td>
            <td>{{ brochure.phone }}</td>
            <td>{{ brochure.purchase_plan }}</td>
            <td>{{ formatDate(brochure.created_at) }}</td>
            <td>
              <select
                v-model="brochure.status"
                class="admin--status-select"
                @change="handleStatusChange(brochure.id, brochure.status)"
              >
                <option value="접수">접수</option>
                <option value="접수완료">접수완료</option>
                <option value="계약완료">계약완료</option>
                <option value="출고완료">출고완료</option>
              </select>
            </td>
            <td>
              <button
                class="admin--btn-small admin--btn-small-danger"
                @click="handleDelete(brochure.id)"
              >
                삭제
              </button>
            </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'

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

const { get, put, del } = useApi()

const isLoading = ref(false)
const brochures = ref([])
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 loadBrochures = async () => {
  isLoading.value = true

  const params = {
    page: currentPage.value,
    per_page: perPage.value
  }

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

  const { data, error } = await get('/service/brochure', params)

  if (data) {
    brochures.value = data.items || []
    totalCount.value = data.total || 0
    totalPages.value = Math.ceil(totalCount.value / perPage.value)
  }

  isLoading.value = false
}

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

const handleReset = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadBrochures()
}

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

const handleExcelDownload = () => {
  const params = searchKeyword.value ? { search_keyword: searchKeyword.value } : {}
  window.open(`/api/service/brochure/excel?${new URLSearchParams(params)}`, '_blank')
}

const handleStatusChange = async (id, status) => {
  const { error } = await put(`/service/brochure/${id}/status`, { status })

  if (error) {
    alert('상태 변경에 실패했습니다.')
    loadBrochures()
  } else {
    alert('상태가 변경되었습니다.')
  }
}

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

  const { error } = await del(`/service/brochure/${id}`)

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

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')}`
}

onMounted(() => {
  loadBrochures()
})
</script>
