<template>
  <div class="admin--showroom-list">
    <!-- 상단 버튼 -->
    <div class="admin--search-box">
      <div class="admin--search-form"></div>
      <div class="admin--search-actions">
        <button class="admin--btn admin--btn-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="isLoading">
            <td colspan="7" class="admin--table-loading">
              데이터를 불러오는 중...
            </td>
          </tr>
          <tr v-else-if="!showrooms || showrooms.length === 0">
            <td colspan="7" class="admin--table-empty">
              등록된 전시장이 없습니다.
            </td>
          </tr>
          <tr v-else v-for="(showroom, index) in showrooms" :key="showroom.id">
            <td>{{ totalCount - ((currentPage - 1) * perPage + index) }}</td>
            <td class="admin--table-title">{{ showroom.name }}</td>
            <td>{{ showroom.branch_name || '-' }}</td>
            <td>{{ showroom.main_phone }}</td>
            <td>{{ showroom.address }}</td>
            <td>
              <button
                class="admin--toggle-btn"
                :class="{ 'is-active': showroom.is_active == 1 }"
                @click="toggleActive(showroom.id, showroom.is_active)"
              >
                {{ showroom.is_active == 1 ? '사용' : '비사용' }}
              </button>
            </td>
            <td>
              <div class="admin--table-actions">
                <button
                  class="admin--btn-small admin--btn-small-primary"
                  @click="goToEdit(showroom.id)"
                >
                  수정
                </button>
                <button
                  class="admin--btn-small admin--btn-small-danger"
                  @click="deleteShowroom(showroom.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>

    <!-- 알림 모달 -->
    <AdminAlertModal
      v-if="alertModal.show"
      :title="alertModal.title"
      :message="alertModal.message"
      :type="alertModal.type"
      @confirm="handleAlertConfirm"
      @cancel="handleAlertCancel"
      @close="closeAlertModal"
    />
  </div>
</template>

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

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

const router = useRouter()
const { get, del, post } = useApi()

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

// 알림 모달
const alertModal = ref({
  show: false,
  title: '알림',
  message: '',
  type: 'alert',
  onConfirm: null
})

// 알림 모달 표시
const showAlert = (message, title = '알림') => {
  alertModal.value = {
    show: true,
    title,
    message,
    type: 'alert',
    onConfirm: null
  }
}

// 확인 모달 표시
const showConfirm = (message, onConfirm, title = '확인') => {
  alertModal.value = {
    show: true,
    title,
    message,
    type: 'confirm',
    onConfirm
  }
}

// 알림 모달 닫기
const closeAlertModal = () => {
  alertModal.value.show = false
}

// 알림 모달 확인
const handleAlertConfirm = () => {
  if (alertModal.value.onConfirm) {
    alertModal.value.onConfirm()
  }
  closeAlertModal()
}

// 알림 모달 취소
const handleAlertCancel = () => {
  closeAlertModal()
}

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

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

  const { data, error } = await get('/showroom/list', { params })

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

  if (data?.success && data?.data) {
    showrooms.value = data.data.items || []
    totalCount.value = data.data.total || 0
    totalPages.value = Math.ceil(totalCount.value / perPage.value)
    console.log('[ShowroomList] 로드 성공:', showrooms.value.length)
  }

  isLoading.value = false
}

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

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

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

// 전시장 삭제
const deleteShowroom = (id) => {
  showConfirm(
    '정말 삭제하시겠습니까?',
    async () => {
      const { data, error } = await del(`/showroom/${id}`)

      if (error || !data?.success) {
        showAlert(error?.message || data?.message || '삭제에 실패했습니다.', '오류')
      } else {
        showAlert(data.message || '전시장이 삭제되었습니다.', '성공')
        loadShowrooms()
      }
    },
    '전시장 삭제'
  )
}

// 사용/비사용 토글
const toggleActive = (id, currentStatus) => {
  console.log('[toggleActive] 호출:', { id, currentStatus })
  const statusText = currentStatus == 1 ? '비사용' : '사용'

  showConfirm(
    `전시장을 ${statusText} 상태로 변경하시겠습니까?`,
    async () => {
      console.log('[toggleActive] API 호출:', `/showroom/${id}/toggle-active`)

      const { data, error } = await post(`/showroom/${id}/toggle-active`)

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

      if (error || !data?.success) {
        console.error('[toggleActive] 에러 상세:', error)
        showAlert(error?.message || data?.message || '상태 변경에 실패했습니다.', '오류')
      } else {
        showAlert(data.message || '전시장 상태가 변경되었습니다.', '성공')
        loadShowrooms()
      }
    },
    '상태 변경'
  )
}

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

.admin--toggle-btn {
  padding: 6px 16px;
  font-size: 12px;
  border-radius: 20px;
  border: 1px solid #ddd;
  background: #f5f5f5;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.admin--toggle-btn:hover {
  border-color: #bbb;
  background: #e8e8e8;
}

.admin--toggle-btn.is-active {
  background: var(--admin-accent-primary);
  color: white;
  border-color: var(--admin-accent-primary);
}

.admin--toggle-btn.is-active:hover {
  background: var(--admin-accent-hover);
  border-color: var(--admin-accent-hover);
}
</style>
