<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="650px"
    class="rounded-2xl overflow-hidden"
    :show-close="false"
    top="5vh"
    append-to-body
    destroy-on-close
  >
    <!-- 自定义头部 -->
    <template #header="{ close, titleId, titleClass }">
      <div class="flex items-center gap-3 py-4 px-2 border-b border-gray-100">
        <el-icon
          class="cursor-pointer hover:text-blue-500 transition-colors"
          @click="close"
          :size="24"
        >
          <IEpArrowLeft />
        </el-icon>
        <span :id="titleId" :class="titleClass" class="text-lg font-bold text-gray-800">
          评论回复
        </span>
      </div>
    </template>

    <div class="flex flex-col h-[75vh]">
      <!-- 中间滚动区域 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar p-6 pt-0">
        <!-- 1. 顶部：父级评论展示 -->
        <div v-if="parentComment" class="flex gap-4 bg-gray-50 p-5 rounded-xl">
          <img
            :src="parentComment.hiddenAvatar"
            class="w-12 h-12 rounded-full object-cover border-2 border-gray-200 flex-shrink-0"
          />
          <div class="flex-1">
            <div class="flex items-center justify-between mb-2">
              <span class="font-bold text-gray-900 text-base">{{ parentComment.hiddenName }}</span>
              <!-- 点赞按钮 -->
              <div
                class="flex items-center gap-1.5 cursor-pointer text-gray-500 hover:text-blue-500 transition-colors px-3 py-1.5 rounded-full hover:bg-blue-50"
                @click="handleLike(parentComment)"
              >
                <el-icon :size="18">
                  <svg-icon :name="parentComment.hasPraise ? 'praise_fill' : 'praise'"></svg-icon>
                </el-icon>
                <span class="text-sm font-medium">{{ parentComment.postPriseCount || 0 }}</span>
              </div>
            </div>

            <div
              class="text-gray-800 text-base leading-relaxed mb-2"
              v-html="parseEmoji(parentComment.content)"
            ></div>

            <!-- 下方图片 -->
            <div class="flex flex-wrap gap-2" v-if="parentComment.imgUrl">
              <div
                v-for="(img, imgIndex) in parentComment.imgUrl.split(',').filter(Boolean)"
                :key="imgIndex"
                class="w-20 h-20 rounded-lg overflow-hidden mb-2 cursor-pointer"
              >
                <el-image
                  :src="img"
                  :preview-teleported="true"
                  class="w-full h-full object-cover"
                  :preview-src-list="parentComment.imgUrl.split(',').filter(Boolean)"
                  :initial-index="imgIndex"
                  fit="cover"
                />
              </div>
            </div>

            <div class="text-sm text-gray-500 flex items-center gap-2">
              <span>{{ dayjs(parentComment.createTime * 1000).format('MM-DD HH:mm') }}</span> ·
              <span class="text-xs text-gray-500">{{ parentComment.region }}</span>
            </div>
          </div>
        </div>

        <!-- 分割线 & 统计 -->
        <div class="h-2.5"></div>
        <div class="text-base font-bold text-gray-800 mb-6 px-1">{{ total }} 条回复</div>

        <!-- 2. 下方：回复列表 -->
        <div v-loading="loading" class="space-y-6">
          <div v-for="(item, index) in list" :key="item.id" class="flex gap-4 relative group">
            <img
              :src="item.avatar"
              class="w-10 h-10 rounded-full object-cover cursor-pointer hover:opacity-80 transition-opacity flex-shrink-0"
            />

            <div class="flex-1 border-b border-gray-100">
              <div class="flex items-center justify-between mb-2">
                <div class="flex items-center gap-1">
                  <span class="font-semibold text-gray-900 text-base">{{ item.replyUser }}</span>
                  <!-- v-if="item.replyName && item.replyName !== parentComment?.replyUser" -->
                  <span class="text-gray-500 text-sm flex items-center gap-1">
                    <el-icon class="mx-1"><IEpCaretRight /></el-icon>
                    {{ item.replyName }}
                  </span>
                </div>

                <!-- 列表项点赞 -->
                <div class="flex items-center gap-4">
                  <div
                    class="flex items-center gap-1.5 cursor-pointer text-gray-500 hover:text-blue-500 transition-colors px-3 py-1.5 rounded-full hover:bg-blue-50"
                    @click="handleReplyInline(item, index)"
                  >
                    <span class="text-sm font-medium">回复</span>
                  </div>
                  <div
                    class="flex items-center gap-1.5 cursor-pointer text-gray-500 hover:text-blue-500 transition-colors px-3 py-1.5 rounded-full hover:bg-blue-50"
                    @click="handleLike(item)"
                  >
                    <el-icon :size="18">
                      <svg-icon :name="item.hasPraise ? 'praise_fill' : 'praise'"></svg-icon>
                    </el-icon>
                    <span class="text-sm font-medium">{{ item.postPriseCount || 0 }}</span>
                  </div>
                </div>
              </div>

              <p
                class="text-gray-700 text-base mb-2 break-all leading-relaxed"
                v-html="parseEmoji(item.content)"
              ></p>
              <!-- 下方图片 -->
              <div class="flex flex-wrap gap-2" v-if="item.imgUrl">
                <div
                  v-for="(img, imgIndex) in item.imgUrl.split(',').filter(Boolean)"
                  :key="imgIndex"
                  class="w-20 h-20 rounded-lg overflow-hidden mb-2 cursor-pointer"
                >
                  <el-image
                    :src="img"
                    :preview-teleported="true"
                    class="w-full h-full object-cover"
                    :preview-src-list="item.imgUrl.split(',').filter(Boolean)"
                    :initial-index="imgIndex"
                    fit="cover"
                  />
                </div>
              </div>

              <div class="text-[14px] text-gray-500 flex items-center gap-2">
                <span>{{ dayjs(item.createTime * 1000).format('MM-DD HH:mm') }}</span> ·
                <span class="text-xs text-gray-500">{{ item.region }}</span>
              </div>

              <!-- 内嵌回复框 -->
              <div
                v-show="currentInlineReplyId === item.id"
                class="mt-4 bg-gray-50 p-4 rounded-xl border border-gray-200 animate-fade-in animate-fade-out"
              >
                <!-- 评论box -->
                <CommentBox
                  v-model:inputText="commentStr"
                  v-model:inputImg="imgUrl"
                  :textAreaHeight="60"
                  :placeholder="`回复 ${item.replyUser}`"
                  :ref="(el) => (replyToOtherBoxRefList[index] = el as HTMLElement)"
                >
                  <template #submit>
                    <el-button
                      :disabled="isDisabled"
                      :loading="loadingBtn"
                      type="primary"
                      @click="submitReply(item.id)"
                      class="px-6 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white text-sm font-medium shadow-sm hover:shadow-md transition-all duration-200"
                      >发表</el-button
                    >
                  </template>
                </CommentBox>
              </div>
            </div>
          </div>

          <!-- 加载更多 / 分页 -->
          <div class="flex justify-end" v-if="total > 0">
            <el-pagination
              v-model:current-page="searchParams.current"
              :page-size="searchParams.size"
              :total="total"
              layout="prev, pager, next,total"
              @current-change="goToPage"
              @size-change="changePageSize"
            />
          </div>

          <el-empty v-if="!loading && list.length === 0" description="暂无回复" :image-size="80" />
        </div>
      </div>

      <!-- 3. 底部固定回复框 -->
      <div
        class="border-t border-gray-100 p-5 bg-white flex items-start gap-4 z-10 shadow-[0_-4px_16px_rgba(0,0,0,0.04)] pb-0"
      >
        <img :src="currentUserAvatar" class="w-10 h-10 rounded-full object-cover flex-shrink-0" />
        <CommentBox
          class="flex-1"
          v-model:inputText="bottomCommentContent"
          v-model:inputImg="bottomImgUrl"
          :textAreaHeight="20"
          :placeholder="`回复 ${parentComment?.replyUser}`"
        />

        <el-button
          type="primary"
          size="large"
          circle
          class="px-6 py-2 bg-blue-500 hover:bg-blue-600 rounded-lg text-white text-sm font-medium shadow-sm hover:shadow-md transition-all duration-200"
          :disabled="!bottomCommentContent.trim() || bottomLoadingBtn"
          @click="submitReply(parentComment?.id)"
        >
          <el-icon :size="20"><IEpPosition /></el-icon>
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { useUserStore } from '@/stores'
import { storeToRefs } from 'pinia'
import {
  getSecondCommentChildren,
  addComment,
  addOrCancelCommentLike,
  getCommentDetail,
} from '@/api'
import type { CommentItemDto } from '@/api'
import { BooleanFlag } from '@/constants'
import { usePageSearch } from '@/hooks'
import { parseEmoji } from '@/utils/emoji'
import CommentBox from '../CommentBox/index.vue'
import dayjs from 'dayjs'
import { push } from 'notivue'

const { articleId, pid } = defineProps<{
  articleId: number
  pid: number
}>()

const emit = defineEmits<{
  (e: 'refresh'): void // 通知父组件刷新
}>()

// Store
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const currentUserAvatar = computed(() => userInfo.value.hiddenAvatar)

// State
const visible = ref(false)
const parentComment = ref<CommentItemDto | null>(null)
const dialogTitle = ref('详情')

// Inline Reply State
const currentInlineReplyId = ref<number | null>(null)
const bottomCommentContent = ref('')
const bottomImgUrl = ref('')
const bottomLoadingBtn = ref(false)
const replyToOtherBoxRefList = ref<HTMLElement[]>([])

const commentStr = ref('')
const imgUrl = ref('')
const loadingBtn = ref(false)
const isDisabled = computed(() => !commentStr.value.trim() || loadingBtn.value)

// --- Actions ---
const { list, total, search, searchParams, goToPage, changePageSize, refresh, loading } =
  usePageSearch(getSecondCommentChildren, {
    defaultParams: {
      articleId: articleId,
      pid: 0,
    },
    immediate: false,
  })

const open = async () => {
  //   const { data } = await getSecondCommentChildren({
  //     pid: item.id,
  //     current: 1,
  //     size: 10,
  //     articleId: articleId,
  //   })
  //   console.log('res', data)
  //   list.value = data.list
  //   parentComment.value = item

  //   // Reset state
  //   currentInlineReplyId.value = null
  //   commentStr.value = ''
  //   bottomCommentContent.value = ''
  console.log('pid', pid)
  await nextTick()
  searchParams.value.pid = pid
  search()
  const { data } = await getCommentDetail(pid)
  console.log('data', data)
  parentComment.value = data
  visible.value = true
}

// 点击列表中的“回复”
const handleReplyInline = (item: CommentItemDto, index: number) => {
  if (currentInlineReplyId.value === item.id) {
    currentInlineReplyId.value = null // Toggle off
  } else {
    currentInlineReplyId.value = item.id
    commentStr.value = '' // Clear previous
    imgUrl.value = ''
    // 聚焦到输入框
    console.log('replyToOtherBoxRefList', replyToOtherBoxRefList.value[index]?.focus)
    replyToOtherBoxRefList.value[index]?.focus()
  }
}

// 提交评论 (共用逻辑)
// targetId: 如果是回复父评论，传 parentComment.id；如果是回复子评论，传 item.id
const submitReply = async (targetId: number | undefined) => {
  if (!targetId) return

  // 判断使用的是哪个输入框的内容
  const isBottom = targetId === parentComment.value?.id
  const content = isBottom ? bottomCommentContent.value : commentStr.value
  const imgStr = isBottom ? bottomImgUrl.value : imgUrl.value
  try {
    if (isBottom) {
      bottomLoadingBtn.value = true
    } else {
      loadingBtn.value = true
    }
    await addComment({
      articleId: articleId,
      content: content,
      pid: targetId, // 这里的pid逻辑根据您的后端接口来，通常回复子评论也是传该子评论ID作为pid
      imgUrl: imgStr,
    })

    push.success('回复成功')

    // 清空输入框
    if (isBottom) {
      bottomCommentContent.value = ''
      bottomImgUrl.value = ''
    } else {
      commentStr.value = ''
      currentInlineReplyId.value = null
    }

    // 刷新列表
    refresh()
    // 通知父组件可能需要更新评论数
    emit('refresh')
  } catch (error) {
    console.error(error)
  } finally {
    if (isBottom) {
      bottomLoadingBtn.value = false
    } else {
      loadingBtn.value = false
    }
  }
}

// 点赞
const handleLike = async (item: CommentItemDto) => {
  try {
    await addOrCancelCommentLike(item.id)
    // 乐观更新 UI
    if (item.hasPraise === BooleanFlag.YES) {
      item.hasPraise = BooleanFlag.NO
      item.postPriseCount--
      push.success('取消点赞成功')
    } else {
      item.hasPraise = BooleanFlag.YES
      item.postPriseCount++
      push.success('点赞成功')
    }
  } catch (error) {
    console.error(error)
  }
}

defineExpose({
  open,
})
</script>

<style scoped lang="scss">
/* 使用 UnoCSS 这里写一些 Element Plus 的样式覆盖 */
:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 0 16px;
}

:deep(.el-dialog__body) {
  padding: 0;
}

/* 自定义滚动条 */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: #e5e7eb;
  border-radius: 4px;
}
.custom-scrollbar::-webkit-scrollbar-track {
  background-color: transparent;
}

.animate-fade-in {
  animation: fadeIn 0.2s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
