<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="editing ? t('Edit Onboarding') : t('Add Onboarding')"
    :positive-text="editing ? t('Save') : t('Add')"
    :negative-text="t('Cancel')"
    @positive-click="handleSubmit"
    @negative-click="handleCancel"
    style="width: 500px;"
  >
    <div class="dialog-content">
      <LinkField
        v-model="formData.onboarding_name"
        :options="'Module Onboarding'"
        :label="t('Onboarding Name')"
        :required="true"
        placeholder=""
        :enable-create="true"
        @create="handleCreateNew"
      />
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { reactive, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { NModal, useMessage } from 'naive-ui'
import { t } from '@/shared/i18n'
import { pageTypeToSlug } from '@/shared/utils/slug'
import LinkField from '@/shared/components/LinkField.vue'

const router = useRouter()

const props = defineProps<{
  show: boolean
  values?: {
    onboarding_name?: string
    name?: string
  }
}>()

const emit = defineEmits<{
  'update:show': [value: boolean]
  'submit': [data: any]
}>()

const message = useMessage()

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

const editing = computed(() => !!props.values?.name)

const formData = reactive({
  onboarding_name: '',
  name: ''
})

watch(() => props.show, (newVal) => {
  if (newVal) {
    if (props.values) {
      formData.onboarding_name = props.values.onboarding_name || ''
      formData.name = props.values.name || ''
    } else {
      formData.onboarding_name = ''
      formData.name = ''
    }
  }
}, { immediate: true })

function handleSubmit() {
  if (!formData.onboarding_name) {
    message.error(t('Please select an onboarding module'))
    return false
  }
  
  const data = { ...formData }
  
  if (!editing.value && !data.name) {
    data.name = `onboarding-${formData.onboarding_name}-${Math.random().toString(36).substring(2, 12)}`
  }
  
  emit('submit', data)
  visible.value = false
  return true
}

function handleCancel() {
  visible.value = false
}

function handleCreateNew() {
  // Close dialog and navigate to new Module Onboarding page with legacy route format
  visible.value = false
  const pagetypeSlug = pageTypeToSlug('Module Onboarding')
  const randomStr = Math.random().toString(36).substring(2, 12)
  const tempName = `new-${pagetypeSlug}-${randomStr}`
  router.push(`/app/${pagetypeSlug}/${tempName}`)
}
</script>

<style scoped>
.dialog-content {
  padding: 16px 0;
}
</style>
