/**
 * 知识库
 */

import { Text, View, Image, ScrollView } from "@tarojs/components";

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import IconA from "@/components/icon/IconA";
import IconQ from "@/components/icon/IconQ";
import { useEffect, useState } from "react";
import CardEditable from "@/components/card/card-editable/index";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  deleteVisitorDislikeAnswer,
  getVisitorDislikeMessages,
} from "@/service/visitor";
import { TVisitorChat } from "@/types/visitor";

import { useModalStore } from "@/store/modalStore";
import { isSuccess } from "@/utils";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";

export default function Index() {
  const router = useRouter();
  const { showModal } = useModalStore();
  const { agentId } = router.params as { agentId: string };
  const [scrollTop, setScrollTop] = useState(0);

  const fetcher = async ([_url, { nextId, pageSize }]) => {
    const res = await getVisitorDislikeMessages({
      agentId,
      startId: nextId,
      pageSize,
    });
    return res.data;
  };
  const { list, loadMore, setSize, pages, pageIndex, mutate } = useLoadMoreInfinite<TVisitorChat[]>(
    createKey(`getVisitorDislikeMessages${agentId}`),
    fetcher
  );

  const dislikeList = list.filter((_item) => _item.role === 'assistant');

  const handleEdit = (item: TVisitorChat) => {
    Taro.navigateTo({
      url: `/pages/dislike-message-editor/index?msgId=${item.msgId}&visitorId=${item.visitorId}&agentId=${item.agentId}`,
    });
  };

  // 删除问答项
  const handleDeleteItem = async (item: TVisitorChat) => {
    
    showModal({
      content: "确定删除该问答项吗？",
      onConfirm: async () => {
        const { status } = await deleteVisitorDislikeAnswer({
          visitorId: item.visitorId,
          msgId: item.msgId,
        });
        if (isSuccess(status)) {
          Taro.showToast({ title: "删除成功", icon: "success" });
          // if (newPages[newPages.length - 1]?.length === 0) {
          //   setSize(size - 1)
          // }
          // 1. 乐观更新：立即移除数据
          mutate((currentPages) => {
            if(currentPages === undefined) return currentPages;
            // 创建全新的 pages 数组（深拷贝）
            const newPages = currentPages.map((page, index) => {
              // 如果不是目标页，直接返回原引用（避免不必要的重渲染）
              if (index !== pageIndex - 1) return page;
              
              // 创建目标页的新副本
              return {
                ...page, // 复制其他属性
                data: page.data.filter(_item => _item.msgId !== item.msgId)
              };
            });
            
            return newPages;
          }, false) // 不重新验证
        }
      },
    });
  };
  const handleView = async (item: TVisitorChat) => {
    Taro.navigateTo({
      url: `/pages/chat-messages/index?visitorId=${item.visitorId}&msgId=${item.msgId}`,
    });
  };

  const onScrollEnd = async () => {
    loadMore();
  };

  useDidShow(() => {
    mutate()
  });

  const createCardOptions = (item: TVisitorChat) => {
    return [
      <View onClick={() => handleDeleteItem(item)}>删除</View>,
      <View onClick={() => handleView(item)}>查看对话</View>,
      <View onClick={() => handleEdit(item)}>编辑</View>,
    ];
  };

  return (
    <PageCustom fullPage>
      <NavBarNormal scrollFadeIn>待处理差评</NavBarNormal>
      <View className="w-full flex flex-col overflow-hidden h-full pt-2">
        <View className="rounded-container-header"></View>
        {/* <View className="text-14 font-medium leading-22 px-16 pb-16">
          问答列表共
          <Text className="text-primary"> 10 </Text>条
        </View> */}
        <ScrollView
          scrollY
          onScrollEnd={onScrollEnd}
          scrollTop={scrollTop}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View className="pb-80">
            {dislikeList.map((item) => {
              return (
                <View className="flex flex-col gap-16 px-16 mb-16">
                  <CardEditable buttons={createCardOptions(item)}>
                    <View className="flex items-start mb-8 gap-8">
                      <View className="flex-center h-28">
                        <IconQ />
                      </View>
                      <View className="flex-1 font-medium text-14 leading-28">
                        {item.content}
                      </View>
                    </View>

                    <View className="flex items-start gap-8">
                      <View className="flex-center  h-28">
                        <IconA />
                      </View>
                      <View className="flex-1 text-12 leading-20 text-gray-45 truncate">
                        <View className="truncate">
                          {item.correctionAnswer}
                        </View>

                        {!!item.correctionLinks?.length && (
                          <View className="pb-12">
                            {item.correctionLinks.map((link) => {
                              return (
                                <View>
                                  查看链接 <Text>{link}</Text>
                                </View>
                              );
                            })}
                          </View>
                        )}
                        {!!item.correctionPics?.length && (
                          <View className="pb-12">
                            {item.correctionPics.map((pic) => {
                              return (
                                <View>
                                  <Image
                                    src={pic}
                                    mode="widthFix"
                                    className="w-full"
                                  ></Image>
                                </View>
                              );
                            })}
                          </View>
                        )}
                      </View>
                    </View>
                  </CardEditable>
                </View>
              );
            })}
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
}
