<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { FormInst } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import CustomModal from '@/components/custom-modal/custom-modal.vue'

const { t } = useI18n()

export interface KnowledgeFormDataInterface {
  knowledgeName: string
  desc: string
  knowledgeType: 'Base' | 'QA'
}

interface Props {
  isShowModal: boolean
  btnLoading: boolean
  knowledgeData: KnowledgeFormDataInterface
}

interface Emits {
  (e: 'update:isShowModal', value: boolean): void
  (e: 'confirm', value: KnowledgeFormDataInterface): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const defaultKnowledgeFormData = {
  knowledgeName: '',
  desc: '',
  knowledgeType: 'Base' as const,
}

const knowledgeFormRef = ref<FormInst | null>(null)

const knowledgeFormData = ref<KnowledgeFormDataInterface>({ ...defaultKnowledgeFormData })

const knowledgeFormDataRules = {
  knowledgeName: [
    { required: true, message: () => t('personal_space_module.knowledge_module.knowledge_name_rule'), trigger: 'blur' },
  ],
}

const showModal = computed({
  get() {
    return props.isShowModal
  },
  set(value: boolean) {
    emit('update:isShowModal', value)
  },
})

const isDisabledConfirmBtn = computed(() => {
  return !knowledgeFormData.value.knowledgeName
})

watch(
  () => showModal.value,
  (newVal) => {
    newVal && (knowledgeFormData.value = JSON.parse(JSON.stringify(props.knowledgeData)))
  },
)

function handleConfirm() {
  knowledgeFormRef.value?.validate((errors) => {
    if (!errors) {
      emit('confirm', knowledgeFormData.value)
    }
  })
}
</script>

<template>
  <CustomModal
    v-model:is-show="showModal"
    :height="364"
    :width="437"
    :title="t('personal_space_module.knowledge_module.edit_knowledge_modal_title')"
    :btn-disabled="isDisabledConfirmBtn"
    :btn-loading="btnLoading"
    @confirm="handleConfirm"
  >
    <template #content>
      <NForm
        ref="knowledgeFormRef"
        :model="knowledgeFormData"
        :rules="knowledgeFormDataRules"
        :label-width="100"
        label-placement="top"
      >
        <NFormItem :label="t('common_module.name')" show-require-mark path="knowledgeName">
          <NInput
            v-model:value="knowledgeFormData.knowledgeName"
            maxlength="15"
            show-count
            type="text"
            :placeholder="t('personal_space_module.knowledge_module.knowledge_name_input_placeholder')"
          />
        </NFormItem>
        <NFormItem :label="t('common_module.desc')">
          <NInput
            v-model:value="knowledgeFormData.desc"
            maxlength="500"
            show-count
            type="textarea"
            :placeholder="t('personal_space_module.knowledge_module.knowledge_desc_input_placeholder')"
          />
        </NFormItem>
      </NForm>
    </template>
  </CustomModal>
</template>
