<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="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
  fileId?: string | null
}>()

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

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

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

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

// Reset form when modal opens
watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.name = ''
      formState.description = ''
    }
  },
)

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

  loading.value = true
  try {
    // Use file-scoped creation when fileId is provided (R1).
    // Fall back to legacy createTable for backward compat.
    let tableId: string | null = null
    if (props.fileId) {
      const table = await store.createTableInFile(
        formState.name.trim(),
        formState.description.trim() || undefined,
      )
      tableId = table?.id ?? null
    } else {
      const table = await store.createTable(
        formState.name.trim(),
        formState.description.trim() || undefined,
      )
      tableId = table?.id ?? null
    }
    if (tableId) emit('success', tableId)
  } catch (err) {
    const { notification } = await import('ant-design-vue')
    notification.error({
      message: '创建失败',
      description: err instanceof Error ? err.message : String(err),
    })
  } finally {
    loading.value = false
  }
}

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