<script setup lang="ts">
import { md } from '@/tools/md.js'
import { onMounted, ref, useTemplateRef } from 'vue'

const { role, msg } = defineProps<{
  role: 'aii' | 'user'
  msg: string
  onMessageEdit: (oldMessage: string, newMessage: string, change: 'aii' | 'user') => void
  onMessageDelete: (message: string, change: 'aii' | 'user') => void
}>()

const showModal = ref(false)

const showEditor = ref(false)
const editorMessage = ref('')

const self = useTemplateRef('self')
const isCollapse = ref(false)

function enableCollapse() {
  self.value?.classList.add('collapse')
  isCollapse.value = true
}

function disableCollapse() {
  self.value?.classList.remove('collapse')
  isCollapse.value = false
}

onMounted(() => {
  editorMessage.value = msg
  if (role === 'aii') {
    enableCollapse()
  }
})
</script>

<template>
  <div :class="[`${role}-message`, 'message']" ref="self">
    <p v-html="md.render(msg)" />
    <n-button class="modify-button" secondary type="info" circle @click="showModal = true">
      ⚙️
    </n-button>
    <n-button
      v-if="role === 'aii'"
      class="collapse-button"
      secondary
      :type="isCollapse ? 'error' : 'info'"
      circle
      @click="
        () => {
          if (isCollapse) {
            disableCollapse()
          } else {
            enableCollapse()
          }
          self!.scrollIntoView({ behavior: 'smooth' })
        }
      "
    >
      🪟
    </n-button>

    <n-modal
      v-model:show="showModal"
      :title="role === 'aii' ? 'AI 生成的内容' : '你输入的内容'"
      preset="card"
      content-scrollable
      style="max-height: 60vh"
    >
      <n-h3 prefix="bar" v-if="showEditor">编辑中</n-h3>
      <n-input v-if="showEditor" type="textarea" :rows="10" v-model:value="editorMessage"></n-input>
      <n-code v-else :code="msg" word-wrap />
      <!--suppress VueUnrecognizedSlot -->
      <template #footer>
        <n-flex align="center" style="padding-top: 10px">
          <n-button v-if="!showEditor" secondary type="info">复制</n-button>
          <n-button v-if="!showEditor" secondary type="warning" @click="showEditor = true">
            编辑
          </n-button>
          <n-button v-if="!showEditor" secondary type="error" @click="onMessageDelete(msg, role)">
            删除
          </n-button>
          <n-button v-if="showEditor" secondary type="info" @click="showEditor = false">
            取消
          </n-button>
          <n-button
            v-if="showEditor"
            secondary
            type="primary"
            @click="
              () => {
                onMessageEdit(msg, editorMessage, role)
                showEditor = false
              }
            "
          >
            保存
          </n-button>
          <n-tag v-if="showEditor" type="warning">保存不会触发 AI 调用。</n-tag>
        </n-flex>
      </template>
    </n-modal>
  </div>
</template>

<style scoped></style>
