<template>
  <section class="flex glass border border-white/35 rounded-[var(--radius-default)] shadow-[var(--shadow-card)] backdrop-blur-[16px] overflow-hidden min-h-[calc(100vh-120px)] max-md:flex-col max-md:min-h-auto">
    <!-- Sidebar -->
    <nav class="w-[180px] flex-shrink-0 bg-white/65 border-r border-white/35 flex flex-col max-md:w-full max-md:border-r-0 max-md:border-b max-md:border-white/35">
      <div class="px-[18px] py-5 pb-3.5 text-base font-bold text-apptext border-b border-white/35 tracking-[0.3px] max-md:px-4 max-md:py-3 max-md:text-[15px]">
        管理后台
      </div>
      <div class="flex flex-col py-2.5 gap-0.5 max-md:flex-row max-md:py-0 max-md:gap-0 max-md:overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        <button
          v-for="item in NAV_ITEMS"
          :key="item.id"
          class="flex items-center gap-2.5 px-[18px] py-2.5 text-[15px] font-medium text-muted bg-transparent border-none cursor-pointer text-left rounded-none transition whitespace-nowrap hover:bg-[rgba(180,154,203,0.1)] hover:text-apptext max-md:flex-col max-md:gap-0.5 max-md:px-3.5 max-md:py-2 max-md:text-xs max-md:flex-shrink-0 max-md:items-center"
          :class="activeSection === item.id ? '!bg-[rgba(180,154,203,0.18)] !text-apptext font-bold border-r-[3px] border-accent max-md:border-r-0 max-md:border-b-[3px]' : ''"
          @click="activeSection = item.id"
          type="button"
        >
          <span class="flex items-center opacity-70 flex-shrink-0" :class="activeSection === item.id ? '!opacity-100' : ''" v-html="item.icon"></span>
          <span>{{ item.label }}</span>
        </button>
      </div>
    </nav>

    <!-- Main content -->
    <div class="flex-1 min-w-0 p-[22px_24px] overflow-auto max-md:p-3.5">
      <!-- Top bar -->
      <div class="flex items-center justify-between mb-[18px] max-md:mb-3">
        <div class="text-xl font-bold text-apptext max-md:text-base">{{ currentNavLabel }}</div>
        <div class="flex gap-2 items-center">
          <button class="ghost inline-flex items-center gap-1.5 text-sm px-3.5 py-1.5" @click="refresh">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/></svg>
            刷新
          </button>
          <button v-if="activeSection === 'products'" class="primary inline-flex items-center gap-1.5 text-sm px-3.5 py-1.5" @click="openCreate">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            添加商品
          </button>
        </div>
      </div>

      <AdminTokenRow
        :show="!token || !!message"
        v-model:token="token"
        :message="!token || message ? message : ''"
        :inline-message="token && message ? message : ''"
      />

      <div v-if="activeSection === 'products'">
        <p class="text-[13px] text-muted mb-2.5">共 {{ products.length }} 件商品</p>
        <AdminProductTable :products="products" @edit="openEdit" @toggle="toggle" @remove="remove" />
      </div>

      <div v-else-if="activeSection === 'orders'">
        <AdminOrderTable :orders="orders" @remove="removeOrder" />
      </div>

      <div v-else-if="activeSection === 'chat'">
        <AdminChatPanel :admin-token="token" />
      </div>

      <div v-else-if="activeSection === 'settings'">
        <AdminMaintenanceRow
          v-model:enabled="maintenanceEnabled"
          v-model:reason="maintenanceReason"
          :message="maintenanceMsg"
          @save="saveMaintenance"
        />
        <AdminSMTPRow :config="smtpConfig" :message="smtpMsg" @save="saveSMTPConfig" />
      </div>

      <div v-else-if="activeSection === 'status'">
        <AdminSystemStatusPanel ref="statusPanelRef" :admin-token="token" />
      </div>
    </div>
  </section>

  <AdminProductModal
    :open="editorOpen"
    :edit-item="selectedItem"
    @close="closeEditor"
    @submit="handleFormSubmit"
  />
</template>

<script setup>
import { computed, onMounted, ref, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  fetchAdminProducts, createProduct, updateProduct, toggleProduct, deleteProduct,
  fetchAdminOrders, deleteAdminOrder,
  fetchSiteMaintenance, setSiteMaintenance,
  fetchSMTPConfig, setSMTPConfig
} from '../shared/api'
import AdminTokenRow from './components/AdminTokenRow.vue'
import AdminMaintenanceRow from './components/AdminMaintenanceRow.vue'
import AdminSMTPRow from './components/AdminSMTPRow.vue'
import AdminProductTable from './components/AdminProductTable.vue'
import AdminProductModal from './components/AdminProductModal.vue'
import AdminOrderTable from './components/AdminOrderTable.vue'
import AdminChatPanel from './components/AdminChatPanel.vue'
import AdminSystemStatusPanel from './components/AdminSystemStatusPanel.vue'

const route = useRoute()
const router = useRouter()

const NAV_ITEMS = [
  { id: 'products', label: '商品管理', icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>' },
  { id: 'orders', label: '订单记录', icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>' },
  { id: 'chat', label: '用户消息', icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>' },
  { id: 'settings', label: '站点设置', icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>' },
  { id: 'status', label: '系统状态', icon: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/><polyline points="6 9 10 13 14 9 18 13"/></svg>' }
]

const activeSection = ref('products')
const currentNavLabel = computed(() => NAV_ITEMS.find(i => i.id === activeSection.value)?.label || '')
const statusPanelRef = ref(null)
const token = ref(route.query.token || '')
const products = ref([])
const orders = ref([])
const message = ref('')
const editorOpen = ref(false)
const selectedItem = ref(null)
const maintenanceEnabled = ref(false)
const maintenanceReason = ref('')
const maintenanceMsg = ref('')
const smtpConfig = ref({})
const smtpMsg = ref('')

const syncQuery = () => { if (token.value) router.replace({ query: { token: token.value } }) }

const refresh = async () => {
  if (activeSection.value === 'status') {
    await nextTick()
    statusPanelRef.value?.load()
    return
  }
  if (!token.value) { message.value = '请先输入 token'; return }
  try {
    const [prods, ords] = await Promise.all([fetchAdminProducts(token.value), fetchAdminOrders(token.value)])
    products.value = prods
    orders.value = ords
    message.value = '数据已更新'
  } catch { message.value = '获取失败，请检查 token' }
}

const loadMaintenance = async () => {
  try {
    const { maintenance, reason } = await fetchSiteMaintenance()
    maintenanceEnabled.value = maintenance
    maintenanceReason.value = reason || ''
  } catch { maintenanceMsg.value = '加载维护状态失败' }
}

const loadSMTPConfig = async () => {
  if (!token.value) return
  try { smtpConfig.value = await fetchSMTPConfig(token.value) } catch { smtpMsg.value = '加载 SMTP 配置失败' }
}

const saveSMTPConfig = async (cfg) => {
  if (!token.value) { smtpMsg.value = '请先输入 token'; return }
  try { await setSMTPConfig(token.value, cfg); smtpMsg.value = '配置已保存'; await loadSMTPConfig() }
  catch { smtpMsg.value = '保存失败，请检查 token' }
}

const saveMaintenance = async () => {
  if (!token.value) { maintenanceMsg.value = '请先输入 token'; return }
  try {
    await setSiteMaintenance(token.value, maintenanceEnabled.value, maintenanceReason.value)
    maintenanceMsg.value = maintenanceEnabled.value ? '维护模式已开启' : '维护模式已关闭'
  } catch { maintenanceMsg.value = '保存失败，请检查 token' }
}

const handleFormSubmit = async (payload) => {
  if (!token.value) { message.value = '请先输入 token'; return }
  try {
    if (payload.id) { await updateProduct(token.value, payload.id, payload); message.value = '已更新商品' }
    else { await createProduct(token.value, payload); message.value = '已新增商品' }
    closeEditor()
    await refresh()
  } catch { message.value = '操作失败，请检查输入' }
}

const toggle = async (item) => {
  if (!token.value) { message.value = '请先输入 token'; return }
  await toggleProduct(token.value, item.id, !item.active)
  await refresh()
}

const remove = async (item) => {
  if (!token.value) { message.value = '请先输入 token'; return }
  await deleteProduct(token.value, item.id)
  await refresh()
}

const removeOrder = async (orderId) => {
  if (!token.value) return
  try { await deleteAdminOrder(token.value, orderId); orders.value = orders.value.filter((o) => o.id !== orderId) }
  catch { message.value = '删除订单失败' }
}

const openCreate = () => { selectedItem.value = null; editorOpen.value = true }
const openEdit = (item) => { selectedItem.value = item; editorOpen.value = true }
const closeEditor = () => { editorOpen.value = false; selectedItem.value = null }

watch(token, (val) => { syncQuery(); if (val) loadSMTPConfig() })

onMounted(async () => {
  await loadMaintenance()
  if (token.value) await Promise.all([refresh(), loadSMTPConfig()])
})
</script>
