<template>
  <div class="work-form-container">
    <h1 class="page-title">{{ isEditing ? '编辑作品' : '新建作品' }}</h1>
    
    <div class="form-container">
      <form @submit.prevent="handleSubmit" class="work-form">
        <!-- Title Field -->
        <div class="form-group">
          <label for="title">作品标题</label>
          <input 
            type="text" 
            id="title" 
            v-model="form.title"
            placeholder="请输入作品标题"
            required
          />
          <div class="error-message" v-if="errors.title">
            {{ errors.title }}
          </div>
        </div>
        
        <!-- Category Field -->
        <div class="form-group">
          <label for="category">分类</label>
          <input 
            type="text" 
            id="category" 
            v-model="form.category"
            placeholder="请输入作品分类"
            required
          />
          <div class="error-message" v-if="errors.category">
            {{ errors.category }}
          </div>
        </div>
        
        <!-- Year Field -->
        <div class="form-group">
          <label for="year">创作年份</label>
          <input 
            type="text" 
            id="year" 
            v-model="form.year"
            placeholder="请输入创作年份"
            required
          />
          <div class="error-message" v-if="errors.year">
            {{ errors.year }}
          </div>
        </div>
        
        <!-- Hero Image Field -->
        <div class="form-group">
          <label for="heroImg">作品主图 URL</label>
          <input 
            type="url" 
            id="heroImg" 
            v-model="form.heroImg"
            placeholder="请输入作品主图 URL"
            required
          />
          <div class="error-message" v-if="errors.heroImg">
            {{ errors.heroImg }}
          </div>
        </div>
        
        <!-- Description Field -->
        <div class="form-group">
          <label for="desc">作品描述</label>
          <textarea 
            id="desc" 
            v-model="form.desc"
            placeholder="请输入作品描述"
            rows="5"
            required
          ></textarea>
          <div class="error-message" v-if="errors.desc">
            {{ errors.desc }}
          </div>
        </div>
        
        <!-- Tech Stack Field (Simplified for now) -->
        <div class="form-group">
          <label for="techStack">技术栈（JSON格式）</label>
          <textarea 
            id="techStack" 
            v-model="techStackJson"
            placeholder='请输入技术栈 JSON，例如：[{"category": "前端", "items": ["Vue 3", "TypeScript"]}]'
            rows="3"
            required
          ></textarea>
          <div class="error-message" v-if="errors.techStack">
            {{ errors.techStack }}
          </div>
        </div>
        
        <!-- Gallery Field (Simplified for now) -->
        <div class="form-group">
          <label for="gallery">作品图库（JSON格式）</label>
          <textarea 
            id="gallery" 
            v-model="galleryJson"
            placeholder='请输入图库 JSON，例如：["image1.jpg", "image2.jpg"]'
            rows="3"
            required
          ></textarea>
          <div class="error-message" v-if="errors.gallery">
            {{ errors.gallery }}
          </div>
        </div>
        
        <!-- Links Field (Simplified for now) -->
        <div class="form-group">
          <label for="links">链接（JSON格式）</label>
          <textarea 
            id="links" 
            v-model="linksJson"
            placeholder='请输入链接 JSON，例如：{"live": "https://example.com"}'
            rows="3"
            required
          ></textarea>
          <div class="error-message" v-if="errors.links">
            {{ errors.links }}
          </div>
        </div>
        
        <!-- Submit Buttons -->
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="handleCancel">
            取消
          </button>
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : (isEditing ? '更新作品' : '创建作品') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { createWork, updateWork, fetchWork } from '../../services/api'

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

// Form state
const isSubmitting = ref(false)
const isEditing = computed(() => !!route.params.id)
const errors = reactive<Record<string, string>>({})

// Form data
const form = reactive({
  title: '',
  category: '',
  year: '',
  heroImg: '',
  desc: '',
  techStack: [] as { category: string; items: string[] }[],
  gallery: [] as string[],
  links: { live: '' }
})

// JSON string representations for easy editing
const techStackJson = ref('[]')
const galleryJson = ref('[]')
const linksJson = ref('{"live": ""}')

// Watch JSON strings and update form data
watch(techStackJson, (newVal) => {
  try {
    form.techStack = JSON.parse(newVal)
    delete errors.techStack
  } catch (e) {
    // Validation will catch this
  }
})

watch(galleryJson, (newVal) => {
  try {
    form.gallery = JSON.parse(newVal)
    delete errors.gallery
  } catch (e) {
    // Validation will catch this
  }
})

watch(linksJson, (newVal) => {
  try {
    form.links = JSON.parse(newVal)
    delete errors.links
  } catch (e) {
    // Validation will catch this
  }
})

// Validation function
const validateForm = (): boolean => {
  // Reset errors
  Object.keys(errors).forEach(key => delete errors[key])
  
  let isValid = true
  
  // Validate title
  if (!form.title.trim()) {
    errors.title = '作品标题不能为空'
    isValid = false
  }
  
  // Validate category
  if (!form.category.trim()) {
    errors.category = '作品分类不能为空'
    isValid = false
  }
  
  // Validate year
  if (!form.year.trim()) {
    errors.year = '创作年份不能为空'
    isValid = false
  }
  
  // Validate hero image
  if (!form.heroImg.trim()) {
    errors.heroImg = '作品主图 URL 不能为空'
    isValid = false
  }
  
  // Validate description
  if (!form.desc.trim()) {
    errors.desc = '作品描述不能为空'
    isValid = false
  }
  
  // Validate tech stack JSON
  try {
    JSON.parse(techStackJson.value)
  } catch (e) {
    errors.techStack = '技术栈 JSON 格式无效'
    isValid = false
  }
  
  // Validate gallery JSON
  try {
    JSON.parse(galleryJson.value)
  } catch (e) {
    errors.gallery = '图库 JSON 格式无效'
    isValid = false
  }
  
  // Validate links JSON
  try {
    JSON.parse(linksJson.value)
  } catch (e) {
    errors.links = '链接 JSON 格式无效'
    isValid = false
  }
  
  return isValid
}

// Submit handler
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  isSubmitting.value = true
  
  try {
    if (isEditing.value) {
      // Update existing work
      await updateWork(route.params.id as string, form)
      toast.success('作品更新成功')
    } else {
      // Create new work
      await createWork(form)
      toast.success('作品创建成功')
    }
    
    // Redirect to works list
    router.push('/admin/works')
  } catch (error: any) {
    console.error('Error submitting form:', error)
    toast.error(error.message || (isEditing.value ? '更新作品失败' : '创建作品失败'))
  } finally {
    isSubmitting.value = false
  }
}

// Cancel handler
const handleCancel = () => {
  router.push('/admin/works')
}

// Lifecycle
onMounted(async () => {
  if (isEditing.value) {
    try {
      const workId = route.params.id as string
      const work = await fetchWork(workId)
      // Populate form with work data
      form.title = work.title
      form.category = work.category
      form.year = work.year
      form.heroImg = work.heroImg
      form.desc = work.desc
      form.techStack = work.techStack
      form.gallery = work.gallery
      form.links = work.links
      
      // Update JSON string representations
      techStackJson.value = JSON.stringify(work.techStack, null, 2)
      galleryJson.value = JSON.stringify(work.gallery, null, 2)
      linksJson.value = JSON.stringify(work.links, null, 2)
    } catch (error: any) {
      console.error('Failed to fetch work data:', error)
      toast.error('加载作品数据失败: ' + (error.message || '未知错误'))
    }
  }
})
</script>

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

.page-title {
  font-size: 1.75rem;
  font-weight: 600;
  color: #d4b383;
  margin-bottom: 1.5rem;
  font-family: 'Inter', sans-serif;
}

.form-container {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.work-form {
  max-width: 800px;
}

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

.form-group label {
  display: block;
  font-size: 0.95rem;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 0.5rem;
  font-family: 'Inter', sans-serif;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  font-size: 0.95rem;
  background: rgba(255, 255, 255, 0.05);
  color: white;
  font-family: 'Inter', sans-serif;
  resize: vertical;
}

.form-group input::placeholder,
.form-group textarea::placeholder,
.form-group select::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #d4b383;
  box-shadow: 0 0 0 3px rgba(212, 179, 131, 0.2);
}

.error-message {
  color: #ef4444;
  font-size: 0.875rem;
  margin-top: 0.25rem;
  font-family: 'Inter', sans-serif;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.cancel-btn {
  padding: 0.75rem 1.5rem;
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  font-family: 'Inter', sans-serif;
}

.cancel-btn:hover {
  background: rgba(212, 179, 131, 0.1);
  border-color: #d4b383;
  color: #d4b383;
}

.submit-btn {
  padding: 0.75rem 1.5rem;
  background-color: #d4b383;
  color: #050505;
  border: 1px solid #d4b383;
  border-radius: 0.5rem;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  font-family: 'Inter', sans-serif;
}

.submit-btn:hover:not(:disabled) {
  background-color: transparent;
  color: #d4b383;
  transform: translateY(-1px);
  box-shadow: 0 0 15px rgba(212, 179, 131, 0.3);
}

.submit-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Responsive Design */
@media (max-width: 768px) {
  .form-container {
    padding: 1.5rem;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}
</style>
