<template>
  <div style="max-width: 1100px">
    <n-breadcrumb style="margin-bottom: 16px">
      <n-breadcrumb-item @click="navigateTo('/admin/gallery')">呼籁旅拍</n-breadcrumb-item>
      <n-breadcrumb-item>{{ isNew ? '新增' : '编辑' }}</n-breadcrumb-item>
    </n-breadcrumb>

    <n-space justify="space-between" align="center" style="margin-bottom: 24px">
      <h1 style="margin: 0; font-size: 20px; font-weight: 600; color: #111827">{{ isNew ? '新增照片' : '编辑照片' }}</h1>
      <n-space>
        <n-button secondary @click="navigateTo('/admin/gallery')">取消</n-button>
        <n-button type="primary" :loading="saving" @click="handleSave">保存</n-button>
      </n-space>
    </n-space>

    <n-card v-if="loadError" style="text-align: center; color: #ef4444">{{ loadError }}</n-card>
    <n-spin v-else-if="pageLoading" style="display: flex; justify-content: center; padding: 60px" />

    <template v-else>
      <div class="form-layout">
        <div class="form-main">
          <n-card title="照片信息">
            <n-form label-placement="top">
              <n-form-item label="标题" required>
                <n-input v-model:value="form.title" placeholder="输入照片标题" />
              </n-form-item>
              <n-grid :cols="2" :x-gap="16">
                <n-gi>
                  <n-form-item label="分类">
                    <n-select v-model:value="form.category" :options="categoryOptions" placeholder="选择分类" clearable />
                  </n-form-item>
                </n-gi>
                <n-gi>
                  <n-form-item label="地点">
                    <n-input v-model:value="form.location" placeholder="拍摄地点" />
                  </n-form-item>
                </n-gi>
              </n-grid>
              <n-form-item label="描述">
                <n-input v-model:value="form.description" type="textarea" :rows="4" placeholder="照片描述（可选）" />
              </n-form-item>
              <n-grid :cols="2" :x-gap="16">
                <n-gi>
                  <n-form-item label="方向">
                    <n-select v-model:value="form.orientation" :options="[{ label: '横屏', value: 'landscape' }, { label: '竖屏', value: 'portrait' }]" />
                  </n-form-item>
                </n-gi>
                <n-gi>
                  <n-form-item label="排序">
                    <n-input-number v-model:value="form.sortOrder" :min="0" style="width: 100%" />
                  </n-form-item>
                </n-gi>
              </n-grid>
            </n-form>
          </n-card>
        </div>

        <div class="form-sidebar">
          <n-card title="发布设置">
            <n-form-item label="状态">
              <n-select v-model:value="form.published" :options="[{ label: '已发布', value: true }, { label: '草稿', value: false }]" />
            </n-form-item>
          </n-card>
          <n-card title="照片">
            <AdminImageUpload v-model="form.image" />
          </n-card>
        </div>
      </div>

      <n-alert v-if="formError" type="error" style="margin-top: 12px">{{ formError }}</n-alert>

      <div class="save-bar">
        <n-button secondary @click="navigateTo('/admin/gallery')">取消</n-button>
        <n-button type="primary" :loading="saving" @click="handleSave">保存</n-button>
      </div>
    </template>
  </div>
</template>

<script setup>
import { NButton, NCard, NSpace, NInput, NInputNumber, NForm, NFormItem, NSelect, NBreadcrumb, NBreadcrumbItem, NSpin, NAlert, NGrid, NGi } from 'naive-ui'
import { useMessage } from 'naive-ui'

definePageMeta({ layout: 'admin', middleware: 'admin' })

const route = useRoute()
const { adminFetch } = useAdmin()
const message = useMessage()

const isNew = computed(() => route.params.id === 'new')
const pageLoading = ref(!isNew.value)
const loadError = ref('')
const saving = ref(false)
const formError = ref('')

const categoryOptions = [
  { label: '草原', value: '草原' }, { label: '森林', value: '森林' },
  { label: '湖泊', value: '湖泊' }, { label: '冬季', value: '冬季' },
  { label: '人文', value: '人文' }, { label: '其他', value: '其他' },
]

const form = ref({
  title: '', category: '', location: '', description: '',
  image: '', orientation: 'landscape', published: true, sortOrder: 0,
})

async function loadItem() {
  if (isNew.value) return
  pageLoading.value = true
  try {
    const data = await adminFetch(`/api/admin/gallery/${route.params.id}`)
    form.value = { ...data, published: !!data.published, image: data.image || '' }
  } catch (e) { loadError.value = e.data?.message || '加载失败' }
  finally { pageLoading.value = false }
}

async function handleSave() {
  if (!form.value.title?.trim()) { formError.value = '标题不能为空'; return }
  if (!form.value.image?.trim()) { formError.value = '请上传照片'; return }
  saving.value = true; formError.value = ''
  try {
    if (isNew.value) {
      await adminFetch('/api/admin/gallery', { method: 'POST', body: form.value })
      message.success('创建成功')
      setTimeout(() => navigateTo('/admin/gallery'), 800)
    } else {
      await adminFetch(`/api/admin/gallery/${route.params.id}`, { method: 'PUT', body: form.value })
      message.success('保存成功')
    }
  } catch (e) { formError.value = e.data?.message || '保存失败' }
  finally { saving.value = false }
}

onMounted(loadItem)
</script>

<style scoped>
.form-layout { display: grid; grid-template-columns: 1fr 300px; gap: 20px; align-items: start; }
.form-main { min-width: 0; }
.form-sidebar { display: flex; flex-direction: column; gap: 16px; }
.save-bar { position: sticky; bottom: 0; display: flex; justify-content: flex-end; gap: 8px; padding: 16px 0; margin-top: 24px; background: #f0f2f5; border-top: 1px solid #e5e7eb; }
</style>
