<script setup lang="ts">
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { Close, Delete } from '@icon-park/vue-next'
import { DataTableColumns } from 'naive-ui'
import { ref, watch } from 'vue'
import { MemoryVariableForm } from './memory-variable-modal.vue'
import { useI18n } from 'vue-i18n'
import {
  fetchDeleteAllLongMemory,
  fetchDeleteLongMemoryByKey,
  fetchGetLongMemoryList,
  fetchGetMemoryVariableList,
} from '@/apis/memory'

interface MemoryVariable {
  key: string
  value: string
}

interface LongMemory {
  date: string
  longMemoryContent: { content: string; time: string }[]
}

interface LongMemoryItem {
  timestamp: string
  content: string
}

const isShowMemoryPreviewModal = defineModel<boolean>()

const props = defineProps<{
  data: string
}>()
const { t } = useI18n()

const memoryVariableColumns = createColumns()
const personalAppConfigStore = usePersonalAppConfigStore()

const memoryVariableData = ref<MemoryVariable[]>([])
const longMemoryList = ref<LongMemory[]>([])

const isMemoryLoading = ref(false)

const memoryTabsInfo = ref([
  {
    id: 1,
    name: 'memoryVariable',
    tabName: t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable'),
  },
])

watch(
  () => personalAppConfigStore.commConfig.variableStructure,
  (newValue) => {
    if (newValue !== null) {
      if (!memoryTabsInfo.value.some((tab) => tab.id === 1)) {
        memoryTabsInfo.value.unshift({
          id: 1,
          name: 'memoryVariable',
          tabName: t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable'),
        })
      }
    } else {
      memoryTabsInfo.value = memoryTabsInfo.value.filter((tab) => tab.id !== 1)
    }
  },
  { immediate: true },
)

watch(
  () => personalAppConfigStore.commConfig.isLongMemory,
  (newValue) => {
    if (newValue === 'Y') {
      if (!memoryTabsInfo.value.some((tab) => tab.id === 2)) {
        memoryTabsInfo.value.push({
          id: 2,
          name: 'memoryFragment',
          tabName: t('personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_fragment'),
        })
      }
    } else {
      memoryTabsInfo.value = memoryTabsInfo.value.filter((tab) => tab.id !== 2)
    }
  },
  { immediate: true },
)

function createColumns(): DataTableColumns<MemoryVariableForm> {
  return [
    {
      title: t('personal_space_module.agent_module.agent_setting_module.agent_config_module.variable_name'),
      key: 'key',
      width: 150,
    },
    {
      title: t('personal_space_module.agent_module.agent_setting_module.agent_config_module.variable_value'),
      key: 'value',
    },
  ]
}

function handlePreviewModalClose() {
  isShowMemoryPreviewModal.value = false
}

function handleDeleteLongMemoryRow(time: string, date: string) {
  const agentId = personalAppConfigStore.baseInfo.agentId
  const timestamp = date + ' ' + time
  window.$message
    .ctWarning(
      t(
        'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_fragment_delete_row_tip_content',
      ),
      t('common_module.delete_tip_title'),
    )
    .then(() => {
      fetchDeleteLongMemoryByKey(agentId, timestamp).then(() => {
        longMemoryList.value = longMemoryList.value
          .map((LongMemoryItem) => {
            LongMemoryItem.longMemoryContent = LongMemoryItem.longMemoryContent.filter((item) => {
              return item.time !== time || LongMemoryItem.date !== date
            })
            return LongMemoryItem
          })
          .filter((memory) => memory.longMemoryContent.length > 0)
        window.$message.success(t('common_module.delete_success_message'))
      })
    })
}

function handleDeleteAllLongMemory() {
  const agentId = personalAppConfigStore.baseInfo.agentId
  window.$message
    .ctWarning(
      t(
        'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_fragment_delete_all_tip_content',
      ),
      t('common_module.delete_tip_title'),
    )
    .then(() => {
      fetchDeleteAllLongMemory(agentId).then(() => {
        longMemoryList.value = []
        window.$message.success(t('common_module.clear_success_message'))
      })
    })
}

function handleGetLongMemoryList() {
  if (personalAppConfigStore.commConfig.isLongMemory === 'Y') {
    fetchGetLongMemoryList(personalAppConfigStore.baseInfo.agentId).then((res) => {
      const updateDate = res.data as LongMemoryItem[]
      const groupedData: { [key: string]: LongMemory } = updateDate.reduce(
        (acc, item: LongMemoryItem) => {
          const [date, time] = item.timestamp.split(' ')
          const content = item.content
          if (!acc[date]) {
            acc[date] = { date: date, longMemoryContent: [] }
          }
          acc[date].longMemoryContent.push({ content: content, time: time })
          return acc
        },
        {} as { [key: string]: LongMemory },
      )
      longMemoryList.value = Object.values(groupedData)
    })
  }
}

function handleGetMemoryVariableList() {
  isMemoryLoading.value = true
  fetchGetMemoryVariableList(personalAppConfigStore.baseInfo.agentId).then((res) => {
    memoryVariableData.value = res.data as MemoryVariable[]
    isMemoryLoading.value = false
  })
}

function handleModalOpenAfter() {
  if (personalAppConfigStore.commConfig.variableStructure !== null) handleGetMemoryVariableList()
  if (personalAppConfigStore.commConfig.isLongMemory === 'Y') handleGetLongMemoryList()
}
</script>

<template>
  <n-modal
    v-model:show="isShowMemoryPreviewModal"
    class="h-auto max-h-[720px]"
    :on-after-enter="handleModalOpenAfter"
    :mask-closable="false"
  >
    <div class="flex flex-col items-center justify-center">
      <div class="max-h-[720px] min-h-[500px] w-[880px] rounded-lg bg-white p-[24px]">
        <div class="flex items-center justify-end text-[20px]">
          <Close theme="outline" size="18" fill="#00000073" class="cursor-pointer" @click="handlePreviewModalClose" />
        </div>
        <div>
          <n-tabs type="line" :default-value="props.data" animated>
            <n-tab-pane v-for="tabs in memoryTabsInfo" :key="tabs.id" :name="tabs.name" :tab="tabs.tabName">
              <div v-show="isMemoryLoading" class="flex h-[370px] items-center justify-center">
                <n-spin size="large" />
              </div>
              <div v-show="!isMemoryLoading">
                <div v-if="tabs.name === 'memoryVariable'" class="flex max-h-[490px] justify-center overflow-y-hidden">
                  <n-data-table :columns="memoryVariableColumns" :max-height="440" :data="memoryVariableData" />
                </div>
                <div v-else>
                  <div v-show="longMemoryList.length !== 0" class="flex w-full justify-end">
                    <n-button
                      strong
                      secondary
                      class="text-theme-color! bg-[#eef3fe]! px-[11px]! py-[5px]! border-[1px]!"
                      @click="handleDeleteAllLongMemory"
                      >{{ t('common_module.wipe_data') }}</n-button
                    >
                  </div>
                  <n-scrollbar style="max-height: 458px">
                    <div
                      v-for="(longMemory, longMemoryIndex) in longMemoryList"
                      :key="longMemoryIndex"
                      class="border-b-[1px] border-[#0505050f] py-[12px]"
                    >
                      <div class="mb-[24px] mt-[12px] text-[16px] font-semibold">
                        {{ longMemory.date }}
                      </div>
                      <div
                        v-for="(longMemoryContent, longMemoryContentIndex) in longMemory.longMemoryContent"
                        :key="longMemoryContentIndex"
                        class="long-memory-content mb-[16px] flex justify-between"
                      >
                        <div class="flex items-center">
                          <div class="w-[80px] text-[#84868c]">{{ longMemoryContent.time }}</div>
                          <div>{{ longMemoryContent.content }}</div>
                        </div>
                        <div class="delete-button mr-[20px] pt-[3px] opacity-0 transition-opacity duration-200">
                          <n-tooltip trigger="hover">
                            <template #trigger>
                              <Delete
                                theme="outline"
                                size="15"
                                fill="#333"
                                :stroke-width="3"
                                class="cursor-pointer"
                                @click="handleDeleteLongMemoryRow(longMemoryContent.time, longMemory.date)"
                              />
                            </template>
                            {{ t('common_module.delete') }}
                          </n-tooltip>
                        </div>
                      </div>
                    </div>
                    <div v-show="longMemoryList.length === 0" class="mt-[60px] flex h-[250px] flex-col items-center">
                      <img src="@/assets/images/empty.png" width="144px" height="100px" />
                      <div class="text-[14px]">{{ t('common_module.empty_data') }}</div>
                    </div>
                  </n-scrollbar>
                </div>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<style lang="scss" scoped>
:deep(.n-tabs) {
  .n-tabs-tab {
    font-size: 20px;
  }

  .n-tabs-bar {
    background-color: #fff;
  }

  .n-tabs-nav {
    &.n-tabs-nav--line-type {
      &.n-tabs-nav--top {
        .n-tabs-nav-scroll-content {
          border-bottom: none;
        }
      }
    }
  }
}

.long-memory-content {
  &:hover .delete-button {
    opacity: 1;
  }
}
</style>
