<template>
  <n-modal
    v-model:show="visible"
    preset="dialog"
    :title="editing ? t('Edit Custom Block') : t('Add Custom Block')"
    :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.custom_block_name"
        :options="'Custom HTML Block'"
        :label="t('Custom Block Name')"
        :required="true"
        placeholder=""
        :enable-create="true"
        @create="handleCreateNew"
        :get-query="getCustomBlockQuery"
      />
    </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?: {
    custom_block_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({
  custom_block_name: '',
  name: ''
})

function getCustomBlockQuery() {
  return {
    query: 'jingrow.desk.pagetype.custom_html_block.custom_html_block.get_custom_blocks_for_user'
  }
}

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

function handleSubmit() {
  if (!formData.custom_block_name) {
    message.error(t('Please select a custom block'))
    return false
  }
  
  const data = { ...formData }
  
  if (!editing.value && !data.name) {
    data.name = `custom_block-${formData.custom_block_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 Custom HTML Block page with legacy route format
  visible.value = false
  const pagetypeSlug = pageTypeToSlug('Custom HTML Block')
  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>
