<script setup lang="ts">
import { onMounted, ref, useTemplateRef, watch, watchEffect } from 'vue'
import { useFocus } from '@vueuse/core'
import { fetchSceneList } from '@/apis/home-agent'

interface SceneConfigItemInterface {
  agentId: string
  agentTitle: string
  agentDesc: string
  agentAvatar: string
}

const showSceneList = defineModel<boolean>('showSceneList', { default: false })
const currentSceneConfig = defineModel<SceneConfigItemInterface | null>('currentSceneConfig', { default: null })

const sceneListContainerRef = useTemplateRef<HTMLParagraphElement>('sceneListContainerRef')
const { focused: sceneListContainerFocus } = useFocus(sceneListContainerRef)

const sceneListConfig = ref<SceneConfigItemInterface[]>([])

watch(
  () => showSceneList.value,
  (isShow) => {
    if (isShow) {
      sceneListContainerFocus.value = true
    }
  },
)

watchEffect(() => {
  if (!sceneListContainerFocus.value && showSceneList.value) {
    showSceneList.value = false
  }
})

onMounted(() => {
  getSceneListConfig()
})

function getSceneListConfig() {
  fetchSceneList<SceneConfigItemInterface[]>().then((res) => {
    if (res.code !== 0) return null

    sceneListConfig.value = res.data
  })
}

function handleSceneSelection(sceneConfig: SceneConfigItemInterface) {
  currentSceneConfig.value = {
    ...sceneConfig,
  }

  showSceneList.value = false
}
</script>

<template>
  <div ref="sceneListContainerRef" class="absolute" tabindex="0">
    <Transition name="scene-menu">
      <ul
        v-show="showSceneList"
        class="z-99 absolute bottom-0 left-0 h-fit w-[192px] select-none rounded-[10px] border border-[#9EA3FF] bg-[#e1e1fc] p-[6px]"
      >
        <template v-if="sceneListConfig.length !== 0">
          <li
            v-for="(sceneItem, index) in sceneListConfig"
            :key="index"
            class="flex cursor-pointer rounded-[10px] px-[9px] py-[7px] text-[14px]"
            :class="{
              'hover:bg-[#D7DAF8]': currentSceneConfig?.agentId !== sceneItem.agentId,
              'bg-[#D2D4FB]': currentSceneConfig?.agentId === sceneItem.agentId,
            }"
            @click="handleSceneSelection(sceneItem)"
          >
            <n-avatar :src="sceneItem.agentAvatar" :size="22" object-fit="contain" class="mr-[6px] shrink-0"></n-avatar>

            <span class="flex-1 overflow-hidden">
              <n-ellipsis>{{ sceneItem.agentTitle }}</n-ellipsis>
            </span>
          </li>
        </template>
        <li v-else class="rounded-[10px] px-[9px] py-[7px] text-[14px]">空数据</li>
      </ul>
    </Transition>
  </div>
</template>

<style lang="scss" scoped>
.scene-menu-enter-active,
.scene-menu-leave-active {
  transition-timing-function: ease-in-out;
  transition-duration: 0.3s;
  transition-property: opacity;
}

.scene-menu-enter-from,
.scene-menu-leave-to {
  overflow: 1;
  opacity: 0;
}
</style>
