<template>
  <a-modal
    :open="open"
    title="新建多维表格文件"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item label="图标" name="icon">
        <a-select
          v-model:value="formState.icon"
          :options="iconOptions"
          :show-search="false"
        />
      </a-form-item>
      <a-form-item label="文件名" name="name">
        <a-input
          v-model:value="formState.name"
          placeholder="请输入文件名"
          :maxlength="100"
        />
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-textarea
          v-model:value="formState.description"
          placeholder="可选，文件用途描述"
          :rows="2"
          :maxlength="500"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance } from 'ant-design-vue'
import { useBitableStore } from '@/stores/bitable'

const props = defineProps<{
  open: boolean
}>()

const emit = defineEmits<{
  (e: 'success', fileId: string): void
  (e: 'cancel'): void
}>()

const store = useBitableStore()
const formRef = ref<FormInstance | null>(null)
const loading = ref(false)

const iconOptions = [
  { label: '📋 表格', value: '📋' },
  { label: '📊 仪表盘', value: '📊' },
  { label: '📝 笔记', value: '📝' },
  { label: '🗂️ 项目', value: '🗂️' },
  { label: '📅 日程', value: '📅' },
  { label: '💼 工作', value: '💼' },
  { label: '🎯 目标', value: '🎯' },
  { label: '📚 知识库', value: '📚' },
]

const formState = reactive({
  name: '',
  icon: '📋',
  description: '',
})

const rules = {
  name: [
    { required: true, message: '请输入文件名', trigger: 'blur' },
    { min: 1, max: 100, message: '文件名长度 1-100', trigger: 'blur' },
  ],
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.name = ''
      formState.icon = '📋'
      formState.description = ''
    }
  },
)

async function handleOk(): Promise<void> {
  try {
    await formRef.value?.validate()
  } catch {
    return
  }

  loading.value = true
  try {
    const file = await store.createFile(
      formState.name.trim(),
      formState.icon,
      formState.description.trim(),
    )
    if (file) emit('success', file.id)
  } finally {
    loading.value = false
  }
}

function handleCancel(): void {
  emit('cancel')
}
</script>
