<template>
  <div class="form-container">
    <h1 class="page-title">{{ isEdit ? '编辑 PPT 模板' : '新建 PPT 模板' }}</h1>

    <div class="form-layout">
      <div class="form-card">
        <form @submit.prevent="submitForm">
          <section class="form-section">
            <h3>基础信息</h3>
            <div class="form-group">
              <label class="form-label">名称</label>
              <input v-model="formData.name" type="text" class="form-input" required />
            </div>
            <div class="form-group">
              <label class="form-label">Slug</label>
              <input
                v-model="formData.slug"
                type="text"
                class="form-input"
                :readonly="isSystemEdit"
                required
              />
            </div>
            <div class="form-group">
              <label class="form-label">描述</label>
              <textarea v-model="formData.description" class="form-input" rows="2" />
            </div>
            <div class="form-row">
              <label class="checkbox-label">
                <input v-model="formData.isDefault" type="checkbox" />
                设为演示默认模板
              </label>
              <label class="checkbox-label">
                <input v-model="formData.isActive" type="checkbox" :disabled="isSystemEdit" />
                启用
              </label>
            </div>
            <div class="form-group">
              <label class="form-label">排序</label>
              <input v-model.number="formData.sortOrder" type="number" class="form-input" />
            </div>
          </section>

          <section class="form-section">
            <h3>配色</h3>
            <div class="color-grid">
              <div v-for="key in colorKeys" :key="key" class="form-group">
                <label class="form-label">{{ colorLabels[key] }}</label>
                <input
                  v-if="key !== 'border'"
                  v-model="formData.config.colors[key]"
                  type="color"
                  class="color-input"
                />
                <input v-model="formData.config.colors[key]" type="text" class="form-input form-input--sm" />
              </div>
            </div>
          </section>

          <section class="form-section">
            <h3>动画</h3>
            <div class="form-grid">
              <div class="form-group">
                <label class="form-label">揭示时长</label>
                <input v-model="formData.config.animation.revealDuration" class="form-input" />
              </div>
              <div class="form-group">
                <label class="form-label">揭示退出</label>
                <input v-model="formData.config.animation.revealLeaveDuration" class="form-input" />
              </div>
              <div class="form-group">
                <label class="form-label">翻页时长</label>
                <input v-model="formData.config.animation.slideDuration" class="form-input" />
              </div>
              <div class="form-group">
                <label class="form-label">布局时长</label>
                <input v-model="formData.config.animation.layoutDuration" class="form-input" />
              </div>
              <div class="form-group">
                <label class="form-label">揭示位移</label>
                <input v-model="formData.config.animation.revealOffset" class="form-input" />
              </div>
              <div class="form-group form-group--wide">
                <label class="form-label">缓动曲线</label>
                <input v-model="formData.config.animation.easing" class="form-input" />
              </div>
            </div>
          </section>

          <section class="form-section">
            <h3>切换效果</h3>
            <div class="form-grid">
              <div class="form-group">
                <label class="form-label">页间切换</label>
                <select v-model="formData.config.transitions.slide" class="form-input">
                  <option value="crossfade">交叉淡入 (crossfade)</option>
                  <option value="fade">纯淡入 (fade)</option>
                  <option value="push">推入 (push)</option>
                </select>
              </div>
              <div class="form-group">
                <label class="form-label">分步揭示</label>
                <select v-model="formData.config.transitions.reveal" class="form-input">
                  <option value="fadeUp">上滑淡入 (fadeUp)</option>
                  <option value="fade">纯淡入 (fade)</option>
                </select>
              </div>
            </div>
          </section>

          <section class="form-section">
            <h3>UI</h3>
            <div class="form-row">
              <label class="checkbox-label">
                <input v-model="formData.config.ui.showThumbnailsDefault" type="checkbox" />
                默认显示缩略图栏
              </label>
            </div>
            <div class="form-group">
              <label class="form-label">幻灯片圆角</label>
              <input v-model="formData.config.ui.canvasBorderRadius" class="form-input" />
            </div>
          </section>

          <div class="form-actions">
            <button type="button" class="btn-secondary" @click="router.back()">取消</button>
            <button type="submit" class="btn-primary">{{ isEdit ? '保存修改' : '创建模板' }}</button>
          </div>
        </form>
      </div>

      <div class="preview-card">
        <h3>实时预览</h3>
        <div class="preview-stage">
          <PptSlideCanvas
            :slide="PPT_TEMPLATE_PREVIEW_SLIDE"
            :visible-step="999"
            :template-vars="previewApplied.templateVars"
            :reveal-transition="previewApplied.revealTransition"
            compact
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PptSlideCanvas from '../../components/ppt/PptSlideCanvas.vue'
import {
  clonePptTemplateConfig,
  createEmptyPptTemplateForm,
  parsePptTemplateConfig,
  PPT_TEMPLATE_PREVIEW_SLIDE,
} from '../../config/pptTemplateDefaults'
import { useToast } from '../../composables/useToast'
import {
  createPptTemplate,
  fetchAdminPptTemplates,
  fetchDefaultPptTemplate,
  updatePptTemplate,
} from '../../services/api'
import type { PptTemplateColors } from '../../types/pptTemplate'
import { applyPptTemplate } from '../../utils/applyPptTemplate'

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

const isEdit = computed(() => !!route.params.id)
const isSystemEdit = ref(false)

const formData = ref(createEmptyPptTemplateForm())

const colorKeys = [
  'bg',
  'text',
  'muted',
  'accent',
  'codeBg',
  'codeText',
  'border',
] as const satisfies readonly (keyof PptTemplateColors)[]

const colorLabels: Record<(typeof colorKeys)[number], string> = {
  bg: '背景',
  text: '正文',
  muted: '次要文字',
  accent: '强调色',
  codeBg: '代码背景',
  codeText: '代码文字',
  border: '边框',
}

const previewApplied = computed(() => applyPptTemplate(formData.value.config))

const loadForCreate = async () => {
  try {
    const defaults = await fetchDefaultPptTemplate()
    formData.value.config = clonePptTemplateConfig(parsePptTemplateConfig(defaults.config))
  } catch (err) {
    console.error(err)
    toast.warning('未能加载系统默认模板，使用内置默认值')
  }
}

const loadForEdit = async () => {
  const id = Number.parseInt(route.params.id as string, 10)
  const list = await fetchAdminPptTemplates()
  const item = list.find((t) => t.id === id)
  if (!item) {
    toast.error('模板不存在')
    router.push('/admin/ppt-templates')
    return
  }
  isSystemEdit.value = item.isSystem
  formData.value = {
    name: item.name,
    slug: item.slug,
    description: item.description || '',
    config: clonePptTemplateConfig(parsePptTemplateConfig(item.config)),
    isDefault: item.isDefault,
    sortOrder: item.sortOrder,
    isActive: item.isActive,
  }
}

const submitForm = async () => {
  try {
    if (isEdit.value) {
      await updatePptTemplate(Number.parseInt(route.params.id as string, 10), formData.value)
      toast.success('更新成功')
    } else {
      await createPptTemplate(formData.value)
      toast.success('创建成功')
    }
    router.push('/admin/ppt-templates')
  } catch (err: unknown) {
    console.error(err)
    toast.error(err instanceof Error ? err.message : '保存失败')
  }
}

onMounted(async () => {
  if (isEdit.value) {
    await loadForEdit()
  } else {
    await loadForCreate()
  }
})
</script>

<style scoped>
.form-container {
  width: 100%;
}

.page-title {
  font-size: 1.75rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  color: #fff;
}

.form-layout {
  display: grid;
  grid-template-columns: 1fr 420px;
  gap: 1.5rem;
  align-items: start;
}

@media (max-width: 1100px) {
  .form-layout {
    grid-template-columns: 1fr;
  }
}

.form-card,
.preview-card {
  background: rgba(255, 255, 255, 0.03);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  padding: 1.25rem;
}

.form-section {
  margin-bottom: 1.5rem;
}

.form-section h3,
.preview-card h3 {
  font-size: 1rem;
  color: #d4b383;
  margin-bottom: 1rem;
}

.form-group {
  margin-bottom: 0.75rem;
}

.form-group--wide {
  grid-column: 1 / -1;
}

.form-label {
  display: block;
  font-size: 0.875rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 0.35rem;
}

.form-input {
  width: 100%;
  padding: 0.5rem 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.375rem;
  color: #fff;
}

.form-input--sm {
  margin-top: 0.35rem;
  font-size: 0.75rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 0.75rem;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 0.75rem;
}

.color-input {
  width: 100%;
  height: 2rem;
  border: none;
  background: transparent;
  cursor: pointer;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 0.75rem;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: rgba(255, 255, 255, 0.85);
  font-size: 0.875rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  margin-top: 1rem;
}

.btn-primary,
.btn-secondary {
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  border: none;
  cursor: pointer;
  font-weight: 600;
}

.btn-primary {
  background: #d4b383;
  color: #1a1a1a;
}

.btn-secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.preview-stage {
  aspect-ratio: 16 / 9;
  overflow: hidden;
  border-radius: 0.375rem;
  border: 1px solid rgba(255, 255, 255, 0.08);
}
</style>
