<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="t('Create New PageType')"
    :positive-text="t('Create & Continue')"
    :negative-text="t('Cancel')"
    :loading="creating"
    @positive-click="handleCreate"
    style="width: 750px; max-height: 90vh;"
  >
    <div style="padding: 16px 0">
      <!-- 第一行：名称、语言、翻译 -->
      <div style="display: grid; grid-template-columns: 2fr 1fr 2fr; gap: 12px; margin-bottom: 16px">
        <div>
          <div class="field-label">{{ t('Name') }} <span style="color: #ef4444">*</span></div>
          <n-input
            v-model:value="form.name"
            :placeholder="''"
            :disabled="creating"
            class="align-input"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 4px">{{ t('Must start with a letter, only letters, numbers, spaces, underscores and hyphens allowed') }}</div>
        </div>
        <div>
          <LinkField
            v-model="form.translationLanguage"
            options="Language"
            :label="t('Language')"
            :disabled="creating"
          />
        </div>
        <div>
          <div class="field-label">{{ t('Translation') }}</div>
          <n-input
            v-model:value="form.translationText"
            :placeholder="''"
            :disabled="creating"
            class="align-input"
          />
        </div>
      </div>

      <!-- 第二行：扩展包、模块 -->
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 16px">
        <div class="link-field-wrapper">
          <LinkField
            v-model="form.package"
            :options="'Package'"
            :label="t('Package')"
            :placeholder="''"
            :enable-create="true"
            @create="openCreatePackage"
          />
        </div>
        <div class="link-field-wrapper">
          <LinkField
            v-model="form.module"
            :options="'Module Def'"
            :label="t('Module')"
            :placeholder="''"
            :required="true"
            :enable-create="true"
            @create="openCreateModule"
          />
        </div>
      </div>
      
      <!-- 复选框选项 -->
      <div style="display: flex; flex-direction: column; gap: 12px">
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isSubmittable" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Is Submittable') }}</span>
          </n-checkbox>
        </div>
        <div style="font-size: 12px; color: #6b7280; margin-top: -8px; margin-left: 24px">
          {{ t('Submittable documents can be submitted and modified, can only be modified or deleted after submission') }}
        </div>
        
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isChild" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Is Child Table') }}</span>
          </n-checkbox>
        </div>
        <div style="font-size: 12px; color: #6b7280; margin-top: -8px; margin-left: 24px">
          {{ t('Child table will be displayed in the form of table collection in the parent PageType') }}
        </div>
        
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isSingle" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Is Single') }}</span>
          </n-checkbox>
        </div>
        <div style="font-size: 12px; color: #6b7280; margin-top: -8px; margin-left: 24px">
          {{ t('Single type has only one record, without name field, saved in tabSingles') }}
        </div>
        
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isTree" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Is Tree') }}</span>
          </n-checkbox>
        </div>
        <div style="font-size: 12px; color: #6b7280; margin-top: -8px; margin-left: 24px">
          {{ t('Tree structure uses parent node collection for nested display') }}
        </div>
        
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isVirtual" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Is Virtual') }}</span>
          </n-checkbox>
        </div>
        
        <div style="display: flex; align-items: flex-start">
          <n-checkbox v-model:checked="form.isCustom" :disabled="creating" size="small">
            <span style="font-size: 13px">{{ t('Custom') }}</span>
          </n-checkbox>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { NModal, NInput, NCheckbox, useMessage } from 'naive-ui'
import axios from 'axios'
import { t } from '@/shared/i18n'
import { getCurrentLocale } from '@/shared/i18n'
import LinkField from '@/shared/components/LinkField.vue'

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

const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
  (e: 'created', name: string): void
}>()

const message = useMessage()
const creating = ref(false)

const visible = computed({
  get: () => props.show,
  set: (val) => emit('update:show', val)
})

// 获取当前语言作为默认值
function getDefaultLanguage() {
  return getCurrentLocale() || 'zh'
}

const form = ref({
  name: '',
  module: '',
  package: '',
  isSubmittable: false,
  isChild: false,
  isSingle: false,
  isTree: false,
  isVirtual: false,
  isCustom: false,
  translationLanguage: getDefaultLanguage(),
  translationText: ''
})

function resetForm() {
  form.value = {
    name: '',
    module: '',
    package: '',
    isSubmittable: false,
    isChild: false,
    isSingle: false,
    isTree: false,
    isVirtual: false,
    isCustom: false,
    translationLanguage: getDefaultLanguage(),
    translationText: ''
  }
}

function openCreatePackage() {
  const randomStr = Math.random().toString(36).substring(2, 12)
  window.open(`/app/package/new-package-${randomStr}`, '_blank')
}

function openCreateModule() {
  const randomStr = Math.random().toString(36).substring(2, 12)
  window.open(`/app/module-def/new-module-def-${randomStr}`, '_blank')
}

async function handleCreate() {
  if (!form.value.name.trim()) {
    message.error(t('Please enter PageType name'))
    return false
  }
  
  if (!form.value.module || !form.value.module.trim()) {
    message.error(t('Please select module'))
    return false
  }
  
  creating.value = true
  try {
    const inputName = form.value.name.trim()
    
    const createData: Record<string, any> = {
      name: inputName,
      module: form.value.module.trim()
    }
    
    if (form.value.package && form.value.package.trim()) {
      createData.package = form.value.package.trim()
    }
    if (form.value.isSubmittable) createData.is_submittable = 1
    if (form.value.isChild) createData.istable = 1
    if (form.value.isSingle) createData.issingle = 1
    if (form.value.isTree) createData.is_tree = 1
    if (form.value.isVirtual) createData.is_virtual = 1
    if (form.value.isCustom) createData.custom = 1
    
    const res = await axios.post('/api/data/PageType', createData)
    
    if (res.data?.data) {
      const recordName = res.data.data.name || inputName
      
      // 如果填写了翻译内容，创建翻译记录
      if (form.value.translationText.trim()) {
        try {
          await axios.post('/api/data/Translation', {
            language: form.value.translationLanguage,
            source_text: inputName,
            translated_text: form.value.translationText.trim()
          })
        } catch (transError: any) {
          console.warn('Failed to create translation:', transError)
          // 翻译创建失败不影响主流程，只显示警告
        }
      }
      
      message.success(t('Created successfully'))
      visible.value = false
      resetForm()
      emit('created', recordName)
    } else {
      message.error(t('Create failed') + ': ' + t('Invalid response format'))
      return false
    }
  } catch (error: any) {
    const errorMsg = error?.response?.data?.detail || error?.response?.data?.message || error?.message || t('Create failed')
    message.error(errorMsg)
    return false
  } finally {
    creating.value = false
  }
  
  return true
}
</script>

<style scoped>
.field-label {
  display: block;
  font-size: 12px;
  font-weight: 500;
  color: var(--n-text-color-3, #666);
  margin-bottom: 6px;
}

.align-input {
  height: 34px;
}
</style>
