<script setup lang="ts">
import { computed, ref, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import CustomModal from '@/components/custom-modal/custom-modal.vue'
import { fetchCustomEventSource } from '@/composables/useEventSource'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { InputInst } from 'naive-ui'
import { useThrottleFn } from '@vueuse/core'

interface Props {
  modalTitle: string
  isShowModal: boolean
  btnLoading: boolean
}

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

const { t } = useI18n()

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

const personalAppConfigStore = usePersonalAppConfigStore()

const agentSystemInputRef = ref<InputInst | null>(null)

const agentSystem = ref('')

const generateAgentSystemLoading = ref(false)

let controller: AbortController | null = null

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

watch(
  () => showModal.value,
  () => {
    showModal.value && handleGenerateAgentSystem()
  },
)

const isDisabledBtn = computed(() => {
  return !agentSystem.value || generateAgentSystemLoading.value
})

function handleGenerateAgentSystem() {
  agentSystem.value = ''
  generateAgentSystemLoading.value = true

  controller = new AbortController()

  fetchCustomEventSource({
    path: '/api/rest/agentApplicationInfoRest/createAgentSystem.json',
    payload: {
      input: personalAppConfigStore.baseInfo.agentSystem,
    },
    controller,
    onResponse: (data) => {
      if (data && data.message) {
        agentSystem.value += data.message

        useThrottleFn(
          () => {
            nextTick(() => {
              agentSystemInputRef.value!.textareaElRef!.scrollTop =
                agentSystemInputRef.value?.textareaElRef?.scrollHeight || 0
            })
          },
          200,
          true,
        )()
      }
    },
    onRequestError: () => {
      blockMessageResponse()
    },
    onError: () => {
      blockMessageResponse()
    },
    onFinally: () => {
      controller = null
      blockMessageResponse()
    },
  })
}

function blockMessageResponse() {
  controller?.abort()
  generateAgentSystemLoading.value = false
}

function handleCloseModal() {
  blockMessageResponse()
}

function handleAdditionalPrompt() {
  emit('confirm', agentSystem.value)
}
</script>

<template>
  <CustomModal
    v-model:is-show="showModal"
    :title="modalTitle"
    :btn-loading="btnLoading"
    :btn-disabled="isDisabledBtn"
    :width="640"
    :height="610"
    :confirm-btn-text="
      t(
        'personal_space_module.agent_module.agent_setting_module.agent_config_module.optimize_system_modal_module.confirm_btn_text',
      )
    "
    @close="handleCloseModal"
    @confirm="handleAdditionalPrompt"
  >
    <template #content>
      <div>
        <NInput
          ref="agentSystemInputRef"
          v-model:value="agentSystem"
          type="textarea"
          :rows="18"
          :disabled="generateAgentSystemLoading"
          placeholder=""
          class="rounded-lg!"
        />

        <div class="mt-2.5">
          <NButton :disabled="generateAgentSystemLoading" class="rounded-md!" @click="handleGenerateAgentSystem">
            {{ t('common_module.regenerate') }}
          </NButton>
        </div>
      </div>
    </template>
  </CustomModal>
</template>
