<template>
  <div class="about-form-container">
    <h1 class="page-title">关于页面管理</h1>
    
    <div class="form-container">
      <form @submit.prevent="handleSubmit" class="about-form">
        <!-- Basic Info Section -->
        <h3 class="section-title">基本信息</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="form-group">
            <label for="name">姓名</label>
            <input 
              type="text" 
              id="name" 
              v-model="form.name"
              placeholder="请输入姓名"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="avatar">头像</label>
            <ImageUpload 
              v-model="form.avatar"
              :category-id="1"
            />
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="form-group">
            <label for="location">所在地</label>
            <input 
              type="text" 
              id="location" 
              v-model="form.location"
              placeholder="例如：中国 · 杭州"
            />
          </div>
          
          <div class="form-group">
            <label for="email">邮箱</label>
            <EmailAutocomplete
              name="email"
              label="邮箱"
              v-model="form.email"
              variant="admin"
              placeholder="example@domain.com"
            />
          </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="form-group">
            <label for="wechat">微信</label>
            <input 
              type="text" 
              id="wechat" 
              v-model="form.wechat"
              placeholder="微信号"
            />
          </div>
          
          <div class="form-group flex items-end pb-3">
            <label class="checkbox-container">
              <input type="checkbox" v-model="form.isPrimary">
              <span class="checkmark"></span>
              <span class="label-text">设为主页展示资料</span>
            </label>
          </div>
        </div>

        <div class="form-group">
          <label for="bio">个人简介 (支持 HTML)</label>
          <textarea 
            id="bio" 
            v-model="form.bio"
            rows="4"
            placeholder="请输入个人简介..."
          ></textarea>
        </div>

        <!-- Tech Stack Section -->
        <h3 class="section-title mt-8">技术栈</h3>
        <div class="form-group">
          <label for="techStack">技术标签 (用英文逗号分隔)</label>
          <input 
            type="text" 
            id="techStack" 
            v-model="techStackInput"
            placeholder="Vue 3, React, TypeScript, Golang..."
          />
          <div class="tech-tags mt-2 flex flex-wrap gap-2" v-if="techStackPreview.length">
            <span v-for="(tag, idx) in techStackPreview" :key="idx" class="badge">{{ tag }}</span>
          </div>
        </div>

        <!-- Experience Section -->
        <h3 class="section-title mt-8 flex justify-between items-center">
          <span>工作经历</span>
          <button type="button" @click="addExperience" class="btn btn-sm btn-secondary">+ 添加经历</button>
        </h3>
        
        <div class="experiences-list space-y-4">
          <div v-for="(exp, index) in form.experiences" :key="index" class="experience-item p-4 border border-white/10 rounded-lg bg-white/5 relative">
            <button type="button" @click="removeExperience(index)" class="absolute top-2 right-2 text-red-500 hover:text-red-400">&times;</button>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div class="form-group mb-0">
                <label class="text-xs text-white/60 mb-1 block">年份/时间段</label>
                <input type="text" v-model="exp.year" placeholder="2023 - 至今" class="text-sm">
              </div>
              <div class="form-group mb-0">
                <label class="text-xs text-white/60 mb-1 block">职位/角色</label>
                <input type="text" v-model="exp.role" placeholder="高级前端工程师" class="text-sm">
              </div>
              <div class="form-group mb-0">
                <label class="text-xs text-white/60 mb-1 block">公司/组织</label>
                <input type="text" v-model="exp.company" placeholder="某某科技有限公司" class="text-sm">
              </div>
            </div>
          </div>
          <div v-if="form.experiences.length === 0" class="text-center text-white/40 py-4">
            暂无工作经历，请点击右上角添加
          </div>
        </div>

        <!-- Submit Buttons -->
        <div class="form-actions mt-8">
          <button type="submit" class="submit-btn" :disabled="isSubmitting">
            {{ isSubmitting ? '提交中...' : (currentProfileId ? '更新资料' : '创建资料') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useToast } from '../../composables/useToast'
import { createAboutProfile, updateAboutProfile, getAdminAboutProfiles, Experience } from '../../services/api'
import ImageUpload from '../../components/admin/ImageUpload.vue'
import EmailAutocomplete from '../../components/ui/EmailAutocomplete.vue'

const toast = useToast()
const isSubmitting = ref(false)
const currentProfileId = ref<number | null>(null)
const loading = ref(true)

const form = reactive({
  name: '',
  avatar: '',
  location: '',
  bio: '',
  email: '',
  wechat: '',
  isPrimary: false,
  experiences: [] as Experience[]
})

const techStackInput = ref('')

const techStackPreview = computed(() => {
  return techStackInput.value.split(',').map(t => t.trim()).filter(t => t)
})

const addExperience = () => {
  form.experiences.push({ year: '', role: '', company: '' })
}

const removeExperience = (index: number) => {
  form.experiences.splice(index, 1)
}

const loadProfile = async () => {
  loading.value = true
  try {
    const profiles = await getAdminAboutProfiles()
    // 获取第一条数据（因为只有一条数据）
    const profile = profiles.length > 0 ? profiles[0] : null
    
    if (profile) {
      currentProfileId.value = profile.id
      form.name = profile.name || ''
      form.avatar = profile.avatar || ''
      form.location = profile.location || ''
      form.bio = profile.bio || ''
      form.email = profile.email || ''
      form.wechat = profile.wechat || ''
      form.isPrimary = profile.isPrimary || false
      form.experiences = profile.experiences || []
      techStackInput.value = (profile.techStack || []).join(', ')
    } else {
      // 没有数据，显示空表单
      currentProfileId.value = null
    }
  } catch (error) {
    console.error('Error loading profile:', error)
    toast.error('加载资料失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  isSubmitting.value = true
  try {
    const payload = {
      ...form,
      techStack: techStackPreview.value
    }

    if (currentProfileId.value) {
      await updateAboutProfile(currentProfileId.value, payload)
      toast.success('资料更新成功')
    } else {
      await createAboutProfile(payload)
      toast.success('资料创建成功')
    }
    // 重新加载数据以获取新创建的 id
    await loadProfile()
  } catch (error: any) {
    console.error('Error submitting form:', error)
    toast.error(error.message || '操作失败')
  } finally {
    isSubmitting.value = false
  }
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.about-form-container {
  width: 100%;
  max-width: 900px;
  margin: 0 auto;
}

.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);
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 2rem;
}

.section-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #d4b383;
  margin-bottom: 1.25rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.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 {
  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;
}

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

.badge {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  font-size: 0.875rem;
  color: rgba(255, 255, 255, 0.9);
}

.checkbox-container {
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 30px;
  cursor: pointer;
  user-select: none;
  color: rgba(255, 255, 255, 0.8);
}

.checkbox-container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  left: 0;
  height: 20px;
  width: 20px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
}

.checkbox-container:hover input ~ .checkmark {
  background-color: rgba(255, 255, 255, 0.2);
}

.checkbox-container input:checked ~ .checkmark {
  background-color: #d4b383;
  border-color: #d4b383;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-container input:checked ~ .checkmark:after {
  display: block;
}

.checkbox-container .checkmark:after {
  left: 7px;
  top: 3px;
  width: 5px;
  height: 10px;
  border: solid #050505;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

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

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

.submit-btn:hover:not(:disabled) {
  background-color: transparent;
  color: #d4b383;
}

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

.btn-secondary {
  background-color: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: 0.25rem 0.75rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background-color: rgba(212, 179, 131, 0.1);
  border-color: #d4b383;
  color: #d4b383;
}
</style>
