<template>
  <a-form layout="vertical">
    <a-form-item label="字段名称">
      <a-input v-model:value="localName" :maxlength="100" />
    </a-form-item>

    <a-form-item label="字段类型">
      <a-select v-model:value="localType" :disabled="!!field" @change="onTypeChange">
        <a-select-option value="text">文本</a-select-option>
        <a-select-option value="number">数字</a-select-option>
        <a-select-option value="date">日期</a-select-option>
        <a-select-option value="select">单选</a-select-option>
        <a-select-option value="multiselect">多选</a-select-option>
        <a-select-option value="formula">公式</a-select-option>
        <a-select-option value="attachment">附件</a-select-option>
        <a-select-option value="image">图片</a-select-option>
      </a-select>
    </a-form-item>

    <!-- Select / Multiselect: options editor -->
    <template v-if="localType === 'select' || localType === 'multiselect'">
      <a-form-item label="选项列表">
        <div
          v-for="(_, idx) in selectOptions"
          :key="idx"
          class="field-config-form__option-row"
        >
          <a-input
            v-model:value="selectOptions[idx]"
            placeholder="选项值"
            :maxlength="200"
          />
          <a-button type="text" danger :icon="h(DeleteOutlined)" @click="removeOption(idx)" />
        </div>
        <a-button type="dashed" block :icon="h(PlusOutlined)" @click="addOption">
          添加选项
        </a-button>
      </a-form-item>
    </template>

    <!-- Formula: expression editor with live validation -->
    <template v-if="localType === 'formula'">
      <a-form-item label="公式表达式">
        <a-textarea
          v-model:value="formulaExpr"
          placeholder="例如: {field_id_1} + {field_id_2} 或 SUM({field_id})"
          :rows="3"
          :maxlength="2000"
        />
        <div class="field-config-form__formula-hint">
          用 {字段ID} 引用其他字段，支持 SUM/AVG/COUNT/MIN/MAX/ABS/ROUND/IF/LEN/CONCAT
        </div>
      </a-form-item>

      <a-form-item v-if="formulaExpr" label="语法校验">
        <a-alert
          v-if="formulaValid === true"
          type="success"
          message="公式语法正确"
          show-icon
        />
        <a-alert
          v-else-if="formulaValid === false"
          type="error"
          :message="formulaError || '公式语法错误'"
          show-icon
        />
        <a-alert v-else type="info" message="校验中..." show-icon />
      </a-form-item>
    </template>

    <!-- Date: format -->
    <template v-if="localType === 'date'">
      <a-form-item label="日期格式">
        <a-select v-model:value="dateFormat">
          <a-select-option value="YYYY-MM-DD">YYYY-MM-DD</a-select-option>
          <a-select-option value="YYYY-MM-DD HH:mm">YYYY-MM-DD HH:mm</a-select-option>
          <a-select-option value="YYYY/MM/DD">YYYY/MM/DD</a-select-option>
        </a-select>
      </a-form-item>
    </template>
  </a-form>
</template>

<script setup lang="ts">
import { ref, watch, h } from 'vue'
import { Button as AButton, Input as AInput, Select as ASelect, Alert as AAlert } from 'ant-design-vue'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { IBitableField, FieldType } from '@/api/bitable'

const props = defineProps<{
  field?: IBitableField | null
}>()

const localName = ref(props.field?.name ?? '')
const localType = ref<FieldType>(props.field?.field_type ?? 'text')
const selectOptions = ref<string[]>(
  (props.field?.config?.options as string[]) ?? [],
)
const formulaExpr = ref((props.field?.config?.formula_expr as string) ?? '')
const dateFormat = ref((props.field?.config?.format as string) ?? 'YYYY-MM-DD')

// Formula validation state
const formulaValid = ref<boolean | null>(null)
const formulaError = ref<string | null>(null)
let validateTimer: ReturnType<typeof setTimeout> | null = null

// Debounced formula validation
watch(formulaExpr, (val) => {
  if (!val.trim()) {
    formulaValid.value = null
    return
  }
  formulaValid.value = null
  if (validateTimer) clearTimeout(validateTimer)
  validateTimer = setTimeout(async () => {
    try {
      const { bitableApi } = await import('@/api/bitable')
      const result = await bitableApi.validateFormula(val)
      formulaValid.value = result.valid
      formulaError.value = result.error ?? null
    } catch (err) {
      formulaValid.value = false
      formulaError.value = err instanceof Error ? err.message : String(err)
    }
  }, 500)
})

function onTypeChange(): void {
  // Reset type-specific config when type changes
  selectOptions.value = []
  formulaExpr.value = ''
  formulaValid.value = null
}

function addOption(): void {
  selectOptions.value.push('')
}

function removeOption(idx: number): void {
  selectOptions.value.splice(idx, 1)
}

// Build config object from current state
function buildConfig(): Record<string, unknown> {
  const config: Record<string, unknown> = {}
  if (localType.value === 'select' || localType.value === 'multiselect') {
    config.options = selectOptions.value.filter((o) => o.trim())
  }
  if (localType.value === 'formula') {
    config.formula_expr = formulaExpr.value
  }
  if (localType.value === 'date') {
    config.format = dateFormat.value
  }
  return config
}

// Expose method for parent to get current form data
defineExpose({
  getData: () => ({
    name: localName.value.trim(),
    fieldType: localType.value,
    config: buildConfig(),
  }),
  isFormulaValid: () => {
    if (localType.value !== 'formula') return true
    if (!formulaExpr.value.trim()) return false
    return formulaValid.value === true
  },
})
</script>

<style scoped>
.field-config-form__option-row {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.field-config-form__formula-hint {
  margin-top: 4px;
  font-size: 12px;
  color: var(--text-secondary, #8c8c8c);
}
</style>
