<script setup lang="ts">
/**
 * 作品列表：本地关键词 + 分类/年份筛选。
 */
import { computed, ref } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useDialog, useToast } from '@wot-ui/ui'
import AppNavbar from '@/components/layout/AppNavbar.vue'
import AppPageShell from '@/components/layout/AppPageShell.vue'
import AdminFilterBar from '../../components/AdminFilterBar.vue'
import { useAdminGuard } from '../../composables/useAdminGuard'
import { adminDelete, adminList, normalizeAdminList, type Work } from '@/api'

const toast = useToast()
const dialog = useDialog()
const { guardAdmin } = useAdminGuard()

const loading = ref(false)
const all = ref<Work[]>([])
const keyword = ref('')
const category = ref('')
const year = ref('')

const categories = computed(() => {
  const set = new Set(all.value.map(w => String(w.category || '')).filter(Boolean))
  return Array.from(set)
})
const years = computed(() => {
  const set = new Set(all.value.map(w => String(w.year || '')).filter(Boolean))
  return Array.from(set).sort().reverse()
})

const list = computed(() => {
  const kw = keyword.value.trim().toLowerCase()
  return all.value.filter((w) => {
    if (kw && !String(w.title || '').toLowerCase().includes(kw)) return false
    if (category.value && String(w.category) !== category.value) return false
    if (year.value && String(w.year) !== year.value) return false
    return true
  })
})

async function load() {
  if (!guardAdmin()) return
  loading.value = true
  try {
    all.value = normalizeAdminList(await adminList('works')) as Work[]
  }
  catch (e: unknown) {
    toast.error(e instanceof Error ? e.message : '加载失败')
  }
  finally {
    loading.value = false
  }
}

onShow(load)

function goCreate() {
  uni.navigateTo({ url: '/subPackages/admin/pages/works/form?mode=create' })
}
function goEdit(item: Work) {
  uni.navigateTo({ url: `/subPackages/admin/pages/works/form?mode=edit&id=${item.id}` })
}
function onDelete(item: Work) {
  dialog.confirm({ title: '确认删除', msg: `确定删除「${item.title}」吗？` }).then(async () => {
    try {
      await adminDelete('works', item.id)
      toast.success('已删除')
      load()
    }
    catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : '删除失败')
    }
  }).catch(() => {})
}
</script>

<template>
  <AppPageShell admin>
    <AppNavbar title="作品管理" show-back />
    <view class="page-pad">
      <AdminFilterBar v-model:keyword="keyword" placeholder="搜索作品" @search="() => {}" @reset="keyword = ''; category = ''; year = ''" />
      <view class="chips">
        <view class="chip" :class="{ on: !category }" @click="category = ''">全部分类</view>
        <view v-for="c in categories" :key="c" class="chip" :class="{ on: category === c }" @click="category = c">{{ c }}</view>
      </view>
      <view class="chips">
        <view class="chip" :class="{ on: !year }" @click="year = ''">全部年份</view>
        <view v-for="y in years" :key="y" class="chip" :class="{ on: year === y }" @click="year = y">{{ y }}</view>
      </view>
      <view v-for="item in list" :key="String(item.id)" class="admin-card row" @click="goEdit(item)">
        <view class="main">
          <text class="title">{{ item.title }}</text>
          <text class="sub text-art-muted">{{ item.category || '—' }} · {{ item.year || '—' }}</text>
        </view>
        <wd-button size="small" type="warning" plain @click.stop="onDelete(item)">删除</wd-button>
      </view>
      <wd-loading v-if="loading" />
      <wd-empty v-if="!loading && !list.length" description="暂无作品" />
    </view>
    <view class="fab" @click="goCreate"><wd-icon name="plus" size="24px" color="#fff" /></view>
  </AppPageShell>
</template>

<style scoped lang="scss">
.page-pad { padding: 24rpx 32rpx 120rpx; }
.chips { display: flex; flex-wrap: wrap; gap: 12rpx; margin-bottom: 16rpx; }
.chip {
  padding: 8rpx 18rpx;
  border-radius: 8rpx;
  font-size: 22rpx;
  background: rgba(255, 255, 255, 0.06);
  color: rgba(255, 255, 255, 0.6);
}
.chip.on { background: rgba(212, 179, 131, 0.25); color: rgb(var(--art-accent)); }
.row { padding: 24rpx 28rpx; margin-bottom: 16rpx; display: flex; align-items: center; gap: 16rpx; }
.main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 8rpx; }
.title { font-size: 30rpx; color: rgb(var(--art-text)); }
.sub { font-size: 24rpx; }
.fab {
  position: fixed; right: 40rpx; bottom: calc(40rpx + env(safe-area-inset-bottom));
  width: 96rpx; height: 96rpx; border-radius: 50%;
  background: rgb(var(--art-accent)); display: flex; align-items: center; justify-content: center; z-index: 100;
}
</style>
