<template>
  <div class="config-form">
    <div class="form-header">
      <div class="form-header-info">
        <el-icon :size="22"><component :is="schema.icon" /></el-icon>
        <div>
          <h2>{{ schema.name }} 配置</h2>
          <span class="form-header-desc">{{ schema.description }}</span>
        </div>
      </div>
      <div class="form-header-actions">
        <el-tooltip content="重置为默认值" placement="top">
          <el-button :icon="RefreshLeft" circle @click="handleReset" />
        </el-tooltip>
      </div>
    </div>

    <el-scrollbar class="form-scroll">
      <el-form
        ref="formRef"
        :model="formData"
        label-position="top"
        class="form-body"
      >
        <div v-for="group in visibleGroups" :key="group.title" class="form-group">
          <div class="form-group-title">
            <span>{{ group.title }}</span>
          </div>

          <template v-for="field in group.fields" :key="field.key">
            <el-form-item
              v-if="isFieldVisible(field)"
              :label="field.label"
              :prop="field.key"
              :rules="getFieldRules(field)"
              class="form-field"
            >
              <template #label="{ label }">
                <span class="field-label">{{ label }}</span>
                <el-tooltip v-if="field.tip" :content="field.tip" placement="top">
                  <el-icon class="field-tip-icon"><InfoFilled /></el-icon>
                </el-tooltip>
              </template>

              <!-- Select -->
              <el-select
                v-if="field.type === 'select'"
                v-model="formData[field.key]"
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="opt in field.options"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>

              <!-- Number -->
              <el-input-number
                v-else-if="field.type === 'number'"
                v-model="formData[field.key]"
                :min="field.min"
                :max="field.max"
                :step="field.step || 1"
                controls-position="right"
                style="width: 100%"
              />

              <!-- Switch -->
              <el-switch
                v-else-if="field.type === 'switch'"
                v-model="formData[field.key]"
                active-text="开启"
                inactive-text="关闭"
              />

              <!-- Text -->
              <el-input
                v-else
                v-model="formData[field.key]"
                :placeholder="field.placeholder || ''"
                clearable
              />
            </el-form-item>
          </template>
        </div>
      </el-form>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { RefreshLeft } from '@element-plus/icons-vue'
import { getDefaultValues } from '../schemas'

const props = defineProps({
  schema: { type: Object, required: true },
})

const emit = defineEmits(['update:config'])

const formRef = ref(null)
const formData = ref({})

function initForm() {
  formData.value = getDefaultValues(props.schema)
  // Load from localStorage
  const saved = localStorage.getItem(`conf-${props.schema.id}`)
  if (saved) {
    try {
      const parsed = JSON.parse(saved)
      formData.value = { ...formData.value, ...parsed }
    } catch (e) {
      // ignore
    }
  }
}

onMounted(initForm)

watch(
  () => props.schema.id,
  () => initForm(),
)

watch(
  formData,
  (val) => {
    emit('update:config', { ...val })
    // Save to localStorage
    localStorage.setItem(`conf-${props.schema.id}`, JSON.stringify(val))
  },
  { deep: true, immediate: true },
)

function isFieldVisible(field) {
  if (!field.dependsOn) return true
  const dep = field.dependsOn
  const val = formData.value[dep.key]
  if ('value' in dep) return val === dep.value
  if ('valueNotIn' in dep) return !dep.valueNotIn.includes(val)
  return true
}

const visibleGroups = computed(() => {
  return props.schema.groups.map((group) => ({
    ...group,
    fields: group.fields.filter(isFieldVisible),
  })).filter((group) => group.fields.length > 0)
})

function getFieldRules(field) {
  if (!field.required) return []
  return [{ required: true, message: `${field.label}不能为空`, trigger: 'blur' }]
}

function handleReset() {
  const defaults = getDefaultValues(props.schema)
  formData.value = { ...defaults }
  localStorage.removeItem(`conf-${props.schema.id}`)
}
</script>

<style scoped>
.config-form {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.form-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.form-header-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.form-header-info h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.form-header-desc {
  font-size: 12px;
  color: #909399;
}

.form-scroll {
  flex: 1;
}

.form-body {
  padding: 16px 20px 40px;
}

.form-group {
  margin-bottom: 8px;
}

.form-group-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  padding: 8px 0;
  margin-bottom: 4px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 6px;
}

.form-group-title::before {
  content: '';
  width: 3px;
  height: 14px;
  background: #667eea;
  border-radius: 2px;
}

.form-field {
  margin-bottom: 18px;
}

.field-label {
  font-size: 13px;
  font-weight: 500;
}

.field-tip-icon {
  margin-left: 4px;
  color: #909399;
  cursor: help;
  font-size: 14px;
}

:deep(.el-form-item__label) {
  padding-bottom: 4px !important;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 40px;
}
</style>
