<template>
  <div class="publish-page">
    <div class="page-header">
      <a-button type="text" @click="$router.back()">
        <arrow-left-outlined /> 返回
      </a-button>
      <h2>发布作品</h2>
    </div>

    <a-spin :spinning="loading">
      <div v-if="work" class="publish-form-wrap">
        <!-- 作品预览 -->
        <div class="preview-card">
          <img v-if="work.coverUrl" :src="work.coverUrl" class="preview-cover" />
          <div class="preview-info">
            <h3>{{ form.title }}</h3>
            <span>{{ work._count?.pages || 0 }} 页绘本</span>
          </div>
        </div>

        <a-form layout="vertical" @finish="handlePublish" class="publish-form">
          <a-form-item label="作品标题" :rules="[{ required: true, message: '请输入标题' }]">
            <a-input v-model:value="form.title" placeholder="给作品取个名字" :maxlength="50" />
          </a-form-item>

          <a-form-item label="作品简介">
            <a-textarea v-model:value="form.description" placeholder="简单介绍一下你的绘本故事" :rows="3" :maxlength="200" show-count />
          </a-form-item>

          <a-form-item label="选择标签">
            <div class="tag-selector">
              <span
                v-for="tag in availableTags"
                :key="tag.id"
                :class="['tag-option', { selected: selectedTagIds.includes(tag.id) }]"
                @click="toggleTag(tag.id)"
              >
                {{ tag.name }}
              </span>
            </div>
          </a-form-item>

          <a-form-item label="可见性">
            <a-radio-group v-model:value="form.visibility">
              <a-radio value="public">公开（所有人可见）</a-radio>
              <a-radio value="private">仅自己可见</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-button
            type="primary"
            html-type="submit"
            block
            size="large"
            :loading="publishing"
            class="publish-btn"
          >
            {{ form.visibility === 'public' ? '提交发布（需审核）' : '保存设置' }}
          </a-button>
        </a-form>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { publicUserWorksApi, type UserWork } from '@/api/public'
import publicApi from '@/api/public'

const route = useRoute()
const router = useRouter()
const workId = Number(route.params.id)

const work = ref<UserWork | null>(null)
const loading = ref(true)
const publishing = ref(false)
const availableTags = ref<Array<{ id: number; name: string; category: string }>>([])
const selectedTagIds = ref<number[]>([])

const form = reactive({
  title: '',
  description: '',
  visibility: 'public' as string,
})

const toggleTag = (tagId: number) => {
  const idx = selectedTagIds.value.indexOf(tagId)
  if (idx >= 0) {
    selectedTagIds.value.splice(idx, 1)
  } else {
    if (selectedTagIds.value.length < 5) {
      selectedTagIds.value.push(tagId)
    } else {
      message.warning('最多选择 5 个标签')
    }
  }
}

const fetchWork = async () => {
  loading.value = true
  try {
    work.value = await publicUserWorksApi.detail(workId)
    form.title = work.value.title
    form.description = work.value.description || ''
    form.visibility = work.value.visibility || 'public'
    selectedTagIds.value = work.value.tags?.map((t) => t.tag.id) || []
  } catch {
    message.error('获取作品详情失败')
  } finally {
    loading.value = false
  }
}

const fetchTags = async () => {
  try {
    const res = await publicApi.get('/public/tags')
    availableTags.value = res as any
  } catch { /* 静默 */ }
}

const handlePublish = async () => {
  publishing.value = true
  try {
    // 先更新作品信息
    await publicUserWorksApi.update(workId, {
      title: form.title,
      description: form.description,
      visibility: form.visibility,
      tagIds: selectedTagIds.value,
    })

    // 如果公开可见，提交发布（进入审核队列）
    if (form.visibility === 'public') {
      await publicUserWorksApi.publish(workId)
      message.success('已提交发布，等待审核')
    } else {
      message.success('设置已保存')
    }

    router.push(`/p/works/${workId}`)
  } catch (err: any) {
    message.error(err?.response?.data?.message || '操作失败')
  } finally {
    publishing.value = false
  }
}

onMounted(() => {
  fetchWork()
  fetchTags()
})
</script>

<style scoped lang="scss">
$primary: #6366f1;

.publish-page {
  max-width: 500px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  h2 { font-size: 18px; font-weight: 700; color: #1e1b4b; margin: 0; }
}

.preview-card {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px;
  background: #fff;
  border-radius: 14px;
  margin-bottom: 20px;
  border: 1px solid rgba($primary, 0.06);

  .preview-cover {
    width: 64px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    flex-shrink: 0;
  }

  .preview-info {
    h3 { font-size: 15px; font-weight: 600; color: #1e1b4b; margin: 0 0 4px; }
    span { font-size: 12px; color: #9ca3af; }
  }
}

.publish-form-wrap {
  .publish-form {
    background: #fff;
    border-radius: 14px;
    padding: 20px;
    border: 1px solid rgba($primary, 0.06);
  }
}

.tag-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .tag-option {
    padding: 4px 12px;
    border-radius: 14px;
    font-size: 12px;
    background: #f3f4f6;
    color: #6b7280;
    cursor: pointer;
    transition: all 0.2s;

    &.selected {
      background: $primary;
      color: #fff;
    }

    &:hover:not(.selected) {
      background: #e5e7eb;
    }
  }
}

.publish-btn {
  height: 48px !important;
  border-radius: 14px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  margin-top: 8px;
}
</style>
