<template>
  <div class="page-dev-create-template">
    <n-card :title="t('Create PageType Template Files')">
      <n-form :model="form" :rules="rules" ref="formRef" label-width="120">
        <n-form-item :label="t('PageType')" path="pagetype">
          <n-select v-model:value="form.pagetype" :options="pagetypeOptions" filterable clearable :loading="loading" :placeholder="t('Select PageType')" @update:show="onDropdownShow" @update:value="onPagetypeChange" />
        </n-form-item>
        <n-form-item :label="t('Create Frontend')">
          <n-switch v-model:value="form.createFrontend" />
        </n-form-item>
        <n-form-item :label="t('Create Backend')">
          <n-switch v-model:value="form.createBackend" />
        </n-form-item>
        <n-form-item>
          <n-button type="primary" :loading="submitting" @click="handleSubmit">{{ t('Create') }}</n-button>
        </n-form-item>
        <n-form-item v-if="appName || moduleName" :label="t('Preview')">
          <div class="preview">
            <div v-if="form.createFrontend && frontendPath">{{ t('Frontend') }}: {{ frontendPath }}</div>
            <div v-if="form.createBackend && backendPath">{{ t('Backend') }}: {{ backendPath }}</div>
          </div>
        </n-form-item>
      </n-form>
      <div v-if="result" class="result">
        <div v-if="result.success">
          <p>{{ t('Created successfully') }}</p>
          <p v-if="result.frontend_path">Frontend: {{ result.frontend_path }}</p>
          <p v-if="result.backend_path">Backend: {{ result.backend_path }}</p>
        </div>
        <div v-else>
          <p style="color:#ef4444">{{ result.message }}</p>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { NCard, NForm, NFormItem, NSelect, NSwitch, NButton, NSpace, useMessage, type FormInst, type FormRules } from 'naive-ui'
import axios from 'axios'
import { t } from '@/shared/i18n'
import { get_session_api_headers } from '@/shared/api/auth'

const router = useRouter()
const message = useMessage()

const loading = ref(false)
const submitting = ref(false)
const result = ref<any>(null)
const formRef = ref<FormInst | null>(null)
const form = ref({ pagetype: '', createFrontend: false, createBackend: true })
const pagetypeOptions = ref<{ label: string; value: string }[]>([])
const appName = ref('')
const moduleName = ref('')

const slug = computed(() => toSnake(form.value.pagetype || ''))
function dotToSlash(s: string): string { return s ? s.split('.').join('/').toLowerCase() : '' }
const frontendPath = computed(() =>
  appName.value && slug.value !== ''
    ? `apps/${appName.value}/frontend/src/views/pagetype/${slug.value}/${slug.value}_toolbar.vue`
    : ''
)
const backendPath = computed(() =>
  appName.value && slug.value !== ''
    ? `apps/${appName.value}/${appName.value}/${dotToSlash(moduleName.value)}/pagetype/${slug.value}/${slug.value}.py`
    : ''
)

const rules: FormRules = {
  pagetype: [{ required: true, message: t('Please select PageType') }]
}


async function onDropdownShow(shown: boolean) {
  if (!shown || pagetypeOptions.value.length) return
  loading.value = true
  try {
    const base = (import.meta as any).env.VITE_JINGROW_SERVER_URL || ''
    const res = await axios.get(`${base}/api/data/PageType`, { params: { order_by: 'modified desc', limit_page_length: 1000 }, headers: get_session_api_headers(), withCredentials: true })
    const list = res.data?.data || []
    pagetypeOptions.value = list.map((x: any) => ({ label: x.name, value: x.name }))
  } catch (e: any) {
    message.error(e?.response?.data?.message || e?.message || 'Failed to load')
  } finally {
    loading.value = false
  }
}

function toSnake(name: string): string {
  return name.replace(/\s+/g, '_').replace(/-+/g, '_').toLowerCase()
}

async function onPagetypeChange() {
  appName.value = ''
  moduleName.value = ''
  if (!form.value.pagetype) return
  try {
    const base = (import.meta as any).env.VITE_JINGROW_SERVER_URL || ''
    const res = await axios.get(`${base}/api/action/jingrow.ai.utils.jlocal.get_pagetype_module_app`, {
      params: { pagetype: form.value.pagetype },
      headers: get_session_api_headers(),
      withCredentials: true
    })
    const msg = res.data?.message || {}
    if (msg?.success) {
      appName.value = msg.app || ''
      moduleName.value = msg.module || ''
    }
  } catch (e) {
    // ignore preview errors
  }
}

async function handleSubmit() {
  formRef.value?.validate(async (errors) => {
    if (errors) return
    submitting.value = true
    try {
      const base = (import.meta as any).env.VITE_JINGROW_SERVER_URL || ''
      const res = await axios.post(`${base}/dev/create-pagetype-template`, {
        pagetype: form.value.pagetype,
        app: appName.value,
        module: moduleName.value,
        create_frontend: form.value.createFrontend,
        create_backend: form.value.createBackend
      }, { headers: get_session_api_headers(), withCredentials: true })
      result.value = res.data
      if (res.data?.success) {
        const { frontend_exists, backend_exists } = res.data
        if (frontend_exists || backend_exists) {
          const parts = []
          if (frontend_exists) parts.push('前端文件')
          if (backend_exists) parts.push('后端文件')
          message.warning(`${parts.join('、')}已存在`)
        } else {
          message.success(t('Created successfully'))
        }
      }
    } catch (e: any) {
      message.error(e?.response?.data?.detail || e?.message || 'Failed')
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
.page-dev-create-template { padding: 16px; }
.result { margin-top: 16px; font-size: 13px; color: #374151; }
</style>


