<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import { Plus, RightOne, MoreOne, Edit, ReduceOne } from '@icon-park/vue-next'
import TimbreSettingModal from './timbre-setting-modal.vue'
import { TimbreLanguageInfoItem } from '../../types'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { fetchGetTimbreInfoDetail } from '@/apis/timber'

const { t } = useI18n()

const personalAppConfigStore = usePersonalAppConfigStore()

const { voiceConfig } = storeToRefs(personalAppConfigStore)

const roleConfigExpandedNames = ref<string[]>([])
const isShowTimbreSettingModal = ref(false)
const timbreInfoDetail = ref<TimbreLanguageInfoItem>()
let timbreInfo = reactive<TimbreLanguageInfoItem>({ language: 0, matchLang: '', timbreInfo: [] })

const timberFullName = computed(() => {
  const languageOptions = [
    { label: 'common_module.mandarin', value: 'zh-CN' },
    { label: 'common_module.cantonese', value: 'zh-HK' },
    { label: 'common_module.english', value: 'en' },
  ]

  const currentLanguage = languageOptions.find((item) => item.value === timbreInfoDetail.value?.matchLang)

  return `${timbreInfoDetail.value?.timbreInfo?.[0]?.timbreName || '--'}(${t(currentLanguage?.label || 'common_module.sound')})`
})

const isHasTimbreId = computed(() => !!voiceConfig.value.timbreId)

onMounted(() => {
  voiceConfig.value.timbreId && handleGetTimberInfoDetail()
})

async function handleGetTimberInfoDetail() {
  const res = await fetchGetTimbreInfoDetail<TimbreLanguageInfoItem>(voiceConfig.value.timbreId)

  if (res.code === 0) {
    timbreInfoDetail.value = res.data
    roleConfigExpandedNames.value = ['timbre']
  }
}

function handleUpdateRoleConfigExpandedNames(expandedNames: string[]) {
  roleConfigExpandedNames.value = expandedNames
}

function handleShowAssociatedTimbreModel() {
  if (voiceConfig.value.timbreId) {
    return
  }

  isShowTimbreSettingModal.value = true
  timbreInfo = { language: 0, matchLang: '', timbreInfo: [] }
}

function handleUpdateTimbreId(timberId: string) {
  isShowTimbreSettingModal.value = false
  voiceConfig.value.timbreId = timberId
  voiceConfig.value.defaultOpen = 'Y'
  handleGetTimberInfoDetail()
}

function handleRemoveTimbreId() {
  voiceConfig.value.timbreId = ''
}

function handleEditAssociatedTimbreModel() {
  isShowTimbreSettingModal.value = true
  timbreInfo = timbreInfoDetail.value!
}
</script>

<template>
  <section class="border-b border-[#e8e9eb] px-5">
    <div class="pt-4">
      <h2 class="my-3 text-[#84868c]">{{ t('common_module.role') }}</h2>

      <NCollapse
        :expanded-names="roleConfigExpandedNames"
        :trigger-areas="['main', 'arrow']"
        @update:expanded-names="handleUpdateRoleConfigExpandedNames"
      >
        <template #arrow>
          <RightOne theme="filled" size="17" fill="#333" :stroke-width="3" />
        </template>

        <NCollapseItem :title="t('common_module.voice')" name="timbre" class="my-[13px]!">
          <template #header-extra>
            <NTooltip trigger="hover">
              <template #trigger>
                <Plus
                  theme="outline"
                  size="22"
                  :stroke-width="3"
                  class="text-theme-color"
                  :class="isHasTimbreId ? 'cursor-not-allowed' : 'cursor-pointer'"
                  @click="handleShowAssociatedTimbreModel"
                />
              </template>
              {{
                isHasTimbreId
                  ? t(
                      'personal_space_module.agent_module.agent_setting_module.agent_config_module.currently_only_one_voice_can_be_set',
                    )
                  : t('personal_space_module.agent_module.agent_setting_module.agent_config_module.setting_voice')
              }}
            </NTooltip>
          </template>

          <span v-show="!voiceConfig.timbreId" class="text-xs text-[#84868c]">
            {{ t('personal_space_module.agent_module.agent_setting_module.agent_config_module.setting_voice_desc') }}
          </span>

          <div class="flex flex-1 flex-wrap items-center gap-[12px] overflow-hidden">
            <div
              v-show="voiceConfig.timbreId"
              class="font-400 line-height-[20px] flex cursor-pointer items-center rounded-[4px] bg-[#f2f5f9] py-[2px] pl-[8px] text-[12px] hover:bg-[#e3e8f0]"
              @click="handleEditAssociatedTimbreModel"
            >
              <div class="max-w-[205px] truncate text-[#151b26]">{{ timberFullName }}</div>

              <n-popover placement="bottom" trigger="hover" :show-arrow="false" class="p-[4px]!">
                <template #trigger>
                  <MoreOne theme="outline" size="14" fill="#333" :stroke-width="3" class="mr-[4px] mt-[2px]" />
                </template>
                <div class="text-[12px]">
                  <div
                    class="flex h-[30px] w-[90px] cursor-pointer items-center justify-start px-[8px] py-[5px] hover:rounded-[4px] hover:bg-[#f2f5f9]"
                    @click="handleEditAssociatedTimbreModel"
                  >
                    <Edit theme="outline" size="16" fill="#333" :stroke-width="3" /><span class="ml-[4px]">
                      {{
                        t(
                          'personal_space_module.agent_module.agent_setting_module.agent_config_module.memory_variable_action_edit',
                        )
                      }}
                    </span>
                  </div>

                  <n-space>
                    <div
                      class="flex h-[30px] w-[90px] cursor-pointer items-center justify-start px-[8px] py-[5px] hover:rounded-[4px] hover:bg-[#f2f5f9]"
                      @click="handleRemoveTimbreId"
                    >
                      <ReduceOne theme="outline" size="16" fill="#333" :stroke-width="3" />
                      <span class="ml-[4px]">
                        {{ t('common_module.delete') }}
                      </span>
                    </div>
                  </n-space>
                </div>
              </n-popover>
            </div>
          </div>
        </NCollapseItem>
      </NCollapse>
    </div>
  </section>

  <TimbreSettingModal
    v-model:is-show-modal="isShowTimbreSettingModal"
    :btn-loading="false"
    :modal-title="t('personal_space_module.agent_module.agent_setting_module.agent_config_module.setting_voice')"
    :timbre-info="timbreInfo"
    @confirm="handleUpdateTimbreId"
  />
</template>
