<script setup lang="ts">
import { Close, Attention, Plus, Help, Delete } from '@icon-park/vue-next'
import { nextTick, ref, shallowReadonly, watch } from 'vue'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { FormInst, FormItemRule, FormRules } from 'naive-ui'
import { useI18n } from 'vue-i18n'
import { cloneDeep } from 'lodash-es'

export interface MemoryVariableForm {
  key: string
  variableDefault: string | null
}

const { t } = useI18n()

const isShowMemoryVariableModal = defineModel<boolean>()

const personalAppConfigStore = usePersonalAppConfigStore()

const memoryVariableTable = ref<MemoryVariableForm[]>([{ key: '', variableDefault: '' }])
const memoryVariableFormRefs = ref<(FormInst | null)[]>([])
const memoryVariableInputRefs = ref<(HTMLInputElement | null)[]>([])

const memoryVariableFormRules = shallowReadonly<FormRules>({
  key: {
    trigger: ['input'],
    validator: (_rule: FormItemRule, value: string) => {
      const regex = /^[\u4e00-\u9fa5a-zA-Z]+$/
      const valueIndex = memoryVariableTable.value.findIndex((item) => item.key === value)
      const updatedMemoryVariableData =
        valueIndex !== -1
          ? [...memoryVariableTable.value.slice(0, valueIndex), ...memoryVariableTable.value.slice(valueIndex + 1)]
          : memoryVariableTable.value
      const hasValue = updatedMemoryVariableData.some((item: { key: string }) => item.key === value)

      if (!value) {
        return new Error(
          t(
            'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_rules.name_not_null',
          ),
        )
      } else if (value.length > 50) {
        return new Error(
          t(
            'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_rules.name_length',
          ),
        )
      } else if (!regex.test(value)) {
        return new Error(
          t(
            'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_rules.name_supports',
          ),
        )
      } else if (hasValue) {
        return new Error(
          t(
            'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_rules.name_not_duplicated',
          ),
        )
      }
      return true
    },
  },
})

watch(
  () => personalAppConfigStore.commConfig.variableStructure,
  (newValue) => {
    if (newValue !== null) {
      memoryVariableTable.value = cloneDeep(newValue)
    } else {
      memoryVariableTable.value = []
    }
  },
  { immediate: true },
)

function handleMemoryPreviewModalClose(refresh = false) {
  isShowMemoryVariableModal.value = false

  memoryVariableTable.value = refresh
    ? memoryVariableTable.value
    : personalAppConfigStore.commConfig.variableStructure
      ? cloneDeep(personalAppConfigStore.commConfig.variableStructure)
      : []

  if (Array.isArray(memoryVariableTable.value)) {
    memoryVariableTable.value = memoryVariableTable.value.filter((item) => item.key)
  } else {
    memoryVariableTable.value = []
  }
}

function handleMemoryVariableFormSave() {
  const validationPromises = memoryVariableTable.value.map((_, index) => {
    const formRef = memoryVariableFormRefs.value[index]
    return new Promise<boolean>((resolve) => {
      if (formRef) {
        formRef.validate((errors: any) => {
          resolve(!errors)
        })
      } else {
        resolve(false)
      }
    })
  })

  Promise.all(validationPromises).then((results) => {
    const isAllValid = results.every((result) => result)

    if (isAllValid) {
      personalAppConfigStore.commConfig.variableStructure = memoryVariableTable.value.length
        ? memoryVariableTable.value
        : null
      handleMemoryPreviewModalClose(true)
      window.$message.success(t('common_module.save_success_message'))
    } else {
      window.$message.error(t('common_module.save_fail_message'))
    }
  })
}

function handleAddMemoryVariableItem() {
  const newVariable = { key: '', variableDefault: '' }
  memoryVariableTable.value.push(newVariable)

  nextTick(() => {
    const newIndex = memoryVariableTable.value.length - 1
    const inputEl = memoryVariableInputRefs.value[newIndex]
    if (inputEl) {
      inputEl.focus()
    }
  })
}

function handleDeleteMemoryVariableRow(rowItem: MemoryVariableForm) {
  const index = memoryVariableTable.value.findIndex((item) => item.key === rowItem.key)
  if (index !== -1) {
    memoryVariableTable.value.splice(index, 1)
  }
}

defineExpose({
  handleAddMemoryVariableItem,
})
</script>

<template>
  <n-modal
    v-model:show="isShowMemoryVariableModal"
    class="h-auto max-h-[720px]"
    :mask-closable="false"
    :auto-focus="false"
    :on-after-leave="handleMemoryPreviewModalClose"
  >
    <div class="flex flex-col items-center justify-center">
      <div class="max-h-[720px] w-[820px] rounded-lg bg-white p-[24px]">
        <div class="flex items-center justify-between text-[20px]">
          <span>
            {{
              t(
                'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.edit_memory_variable',
              )
            }}</span
          >
          <Close
            theme="outline"
            size="18"
            fill="#00000073"
            class="cursor-pointer"
            @click="isShowMemoryVariableModal = false"
          />
        </div>
        <div
          class="mb-[12px] mt-[16px] flex items-center justify-center rounded-[4px] bg-[#FFF4E6] px-[15px] pb-[3px] pt-[4px]"
        >
          <div class="mr-[5px] h-[14px] w-[14px]">
            <Attention
              theme="multi-color"
              size="14"
              :fill="['#ff9326', '#ff9326', '#FFF', '#43CCF8']"
              :stroke-width="3"
            />
          </div>
          <div class="text-[14px] text-[#151B26]">
            {{
              t(
                'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_message_tip',
              )
            }}
          </div>
        </div>
        <div>
          <n-scrollbar style="max-height: 450px; overflow: hidden">
            <div class="flex justify-center">
              <table class="w-full">
                <thead class="sticky top-[0px] z-20 text-[#5c5f66]">
                  <tr class="bg-[#f2f5f9]">
                    <th class="px-[24px] py-[10px] font-normal">
                      <div class="flex">
                        <div>
                          {{
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_name',
                            )
                          }}
                        </div>
                        <span class="ml-[3px] text-[#ff6966]">*</span>
                      </div>
                    </th>
                    <th class="px-[24px] py-[10px] font-normal">
                      <div class="flex items-center">
                        <div class="mr-[2px]" style="margin-right: 7px">
                          {{
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_default_value',
                            )
                          }}
                        </div>
                        <n-popover trigger="hover" class="p-[12px]!">
                          <template #trigger>
                            <Help theme="outline" size="15" fill="#333" :stroke-width="3" class="mt-[2px]" />
                          </template>
                          <div class="mb-[8px] w-[226px]">
                            {{
                              t(
                                'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.default_value_tip',
                              )
                            }}
                          </div>
                          <div>
                            <span class="w-[86px] rounded-[4px] bg-[#f2f5f9] px-[8px] py-[4px]">{{
                              t(
                                'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.default_value_tip_example',
                              )
                            }}</span>
                          </div>
                        </n-popover>
                      </div>
                    </th>
                    <th class="px-[12px] py-[10px] font-normal">
                      {{
                        t(
                          'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_action',
                        )
                      }}
                    </th>
                  </tr>
                </thead>
                <tbody v-if="memoryVariableTable.length !== 0">
                  <tr v-for="(item, index) in memoryVariableTable" :key="index">
                    <td class="pl-[12px]">
                      <n-form
                        :ref="(el: any) => (memoryVariableFormRefs[index] = el)"
                        label-width="auto"
                        :model="item"
                        :rules="memoryVariableFormRules"
                        :show-label="false"
                      >
                        <n-form-item path="key" :show-label="false">
                          <n-popover trigger="click" placement="right" class="p-[12px]!">
                            <template #trigger>
                              <n-input
                                :ref="(el: HTMLInputElement) => (memoryVariableInputRefs[index] = el)"
                                v-model:value="item.key"
                                :placeholder="
                                  t(
                                    'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.name_placeholder',
                                  )
                                "
                                maxlength="50"
                                show-count
                              />
                            </template>
                            <div class="w-[226px]">
                              {{
                                t(
                                  'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_name_tip',
                                )
                              }}
                            </div>
                            <div>
                              {{
                                t(
                                  'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_name_content',
                                )
                              }}
                            </div>
                            <div>
                              {{
                                t(
                                  'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_table_name_length',
                                )
                              }}
                            </div>
                          </n-popover>
                        </n-form-item>
                      </n-form>
                    </td>
                    <td class="pl-[12px]">
                      <n-form-item path="variableDefault" :show-label="false">
                        <n-input
                          v-model:value="item.variableDefault"
                          type="text"
                          :placeholder="
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.default_value_placeholder',
                            )
                          "
                          :maxlength="400"
                          show-count
                        />
                      </n-form-item>
                    </td>
                    <td class="ml-[15px] mt-[5px] flex pl-[12px]">
                      <n-tooltip trigger="hover">
                        <template #trigger>
                          <Delete
                            theme="outline"
                            size="15"
                            fill="#333"
                            :stroke-width="3"
                            class="mt-[2px] cursor-pointer"
                            @click="handleDeleteMemoryVariableRow(item)"
                          />
                        </template>
                        {{ t('common_module.delete') }}
                      </n-tooltip>
                    </td>
                  </tr>
                </tbody>
                <tbody v-else>
                  <tr>
                    <td colspan="3">
                      <div class="flex h-[286px] flex-col items-center">
                        <img src="@/assets/images/empty.png" width="235px" height="160px" />
                        <div class="text-[18px]">
                          {{
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.none_memory_variable',
                            )
                          }}
                        </div>
                        <div class="mt-[12px] text-[14px] text-[#84868c]">
                          {{
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.add_variable_message',
                            )
                          }}
                        </div>
                        <div
                          class="text-theme-color mt-[6px] flex min-w-[78px] cursor-pointer"
                          @click="handleAddMemoryVariableItem"
                        >
                          <Plus theme="outline" size="22" :stroke-width="3" class="text-theme-color" />
                          <span>{{
                            t(
                              'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.memory_variable_add_now',
                            )
                          }}</span>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </n-scrollbar>
          <div v-show="memoryVariableTable.length !== 0" class="text-theme-color mt-[16px] flex min-w-[78px]">
            <Plus
              theme="outline"
              size="22"
              :stroke-width="3"
              class="text-theme-color cursor-pointer"
              @click="handleAddMemoryVariableItem"
            />

            <span class="cursor-pointer" @click="handleAddMemoryVariableItem">{{
              t(
                'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_modal.add_variable',
              )
            }}</span>
          </div>
          <div class="mt-[24px] flex justify-end">
            <button
              class="hover:text-theme-color hover:border-theme-color !mr-[12px] box-content !h-[38px] !w-[74px] cursor-pointer rounded-[6px] border-[1px] border-solid border-[#dde3f0] px-[10px] outline-none transition-all duration-300 hover:border-[theme-color]"
              @click="isShowMemoryVariableModal = false"
            >
              {{ t('common_module.cancel_btn_text') }}
            </button>
            <button
              class="bg-theme-color !box-content !h-[38px] !w-[74px] cursor-pointer rounded-[6px] border-[1px] border-solid border-[#dde3f0] bg-[te] px-[10px] text-[#ffffff] transition-all duration-300 hover:bg-[#528EFF]"
              @click="handleMemoryVariableFormSave()"
            >
              {{ t('common_module.preservation') }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<style lang="scss" scoped>
tbody tr:first-child td {
  padding-top: 10px;
}
</style>
