<template>
  <div class="edit-page">
    <!-- 面包屑 -->
    <NBreadcrumb class="page-breadcrumb">
      <NBreadcrumbItem>
        <NuxtLink to="/admin/reviews">客户评价</NuxtLink>
      </NBreadcrumbItem>
      <NBreadcrumbItem>{{ isNew ? '新增' : '编辑' }}</NBreadcrumbItem>
    </NBreadcrumb>

    <!-- 页头 -->
    <div class="page-header">
      <h1>{{ isNew ? '新增评价' : '编辑评价' }}</h1>
      <div class="header-actions">
        <NButton @click="navigateTo('/admin/reviews')">取消</NButton>
        <NButton type="primary" :loading="saving" :disabled="saving" @click="handleSave">
          保存
        </NButton>
      </div>
    </div>

    <!-- 加载 / 错误状态 -->
    <div v-if="loadError" style="color: #ef4444; padding: 16px;">{{ loadError }}</div>
    <div v-else-if="pageLoading" style="text-align: center; padding: 60px;">
      <NSpin size="large" />
    </div>

    <template v-else>
      <!-- 双栏布局 -->
      <NGrid :cols="4" :x-gap="20" :y-gap="20" class="form-grid">
        <!-- 主区（3列） -->
        <NGi :span="3">
          <NCard title="基本信息">
            <NForm label-placement="top" :show-feedback="false">
              <NFormItem label="客户" required>
                <NInput v-model:value="form.author" placeholder="输入客户名称" />
              </NFormItem>
              <NFormItem label="评分">
                <NRate v-model:value="form.rating" :count="5" />
              </NFormItem>
              <NFormItem label="产品版本">
                <NInput v-model:value="form.title" placeholder="输入产品版本" />
              </NFormItem>
              <NFormItem label="出行日期">
                <NInput v-model:value="form.date" placeholder="如：2026年3月" />
              </NFormItem>
              <NFormItem label="内容" required>
                <NInput
                  v-model:value="form.content"
                  type="textarea"
                  :rows="8"
                  placeholder="输入评价内容"
                />
              </NFormItem>
            </NForm>
          </NCard>
        </NGi>

        <!-- 侧栏（1列） -->
        <NGi :span="1">
          <NCard title="发布设置">
            <NForm label-placement="top" :show-feedback="false">
              <NFormItem label="状态">
                <NSelect
                  v-model:value="form.published"
                  :options="publishedOptions"
                />
              </NFormItem>
              <NFormItem label="已验证">
                <NSwitch v-model:value="form.verified" />
              </NFormItem>
            </NForm>
          </NCard>
        </NGi>
      </NGrid>

      <!-- 底部 sticky 保存栏 -->
      <div class="save-bar">
        <NButton @click="navigateTo('/admin/reviews')">取消</NButton>
        <NButton type="primary" :loading="saving" :disabled="saving" @click="handleSave">
          保存
        </NButton>
      </div>
    </template>
  </div>
</template>

<script setup>
import {
  NButton, NCard, NForm, NFormItem, NInput, NSelect, NSwitch, NRate,
  NBreadcrumb, NBreadcrumbItem, NGrid, NGi, NSpin, 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 form = ref({
  author: '',
  title: '',
  date: '',
  content: '',
  rating: 5,
  published: true,
  verified: false,
})

const publishedOptions = [
  { label: '已发布', value: true },
  { label: '草稿', value: false },
]

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

async function handleSave() {
  if (!form.value.author?.trim()) { message.error('客户名称不能为空'); return }
  if (!form.value.content?.trim()) { message.error('内容不能为空'); return }

  saving.value = true
  try {
    if (isNew.value) {
      await adminFetch('/api/admin/reviews', { method: 'POST', body: form.value })
      message.success('创建成功')
      setTimeout(() => navigateTo('/admin/reviews'), 800)
    } else {
      await adminFetch(`/api/admin/reviews/${route.params.id}`, { method: 'PUT', body: form.value })
      message.success('保存成功')
    }
  } catch (e) {
    message.error(e.data?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(loadItem)
</script>

<style scoped>
.edit-page {
  max-width: 1100px;
}

.page-breadcrumb {
  margin-bottom: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #111827;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.form-grid {
  margin-bottom: 0;
}

.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>
