import { View, ScrollView } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import NavBarNormal from "@/components/nav-bar-normal/index";
import PageCustom from "@/components/page-custom/index";
import IconArrowDownRounded from "@/components/icon/IconArrowDownRounded";
import { useEffect, useState } from "react";
import { useAgentStore } from "@/store/agentStore";
import { isSuccess } from "@/utils";
import ChatMessage from "@/components/chat-message";
import { getVisitorInfo } from "@/service/visitor";
import { TVisitorAgent, TVisitorMessage } from "@/types/visitor";
import type { TMessage, TRobotMessage } from "@/store/textChat";
import VisitorSummary from "./components/VisitorSummary";

import { useVisitorMessages } from "./visitedDetail";
import style from "./index.module.less";

export default () => {
  const router = useRouter();
  const { visitorId } = router.params;
  if (!visitorId) {
    return <View>...</View>;
  }

  const [visitor, setVisitor] = useState<TVisitorAgent>();
  const [list, setList] = useState<
    (TMessage & TRobotMessage & TVisitorMessage)[]
  >([]);

  const fetchData = async () => {
    if (visitorId) {
      const response = await getVisitorInfo(visitorId);
      if (isSuccess(response.status)) {
        setVisitor(response.data);
      }
    }
  };

  const { data, loadMore } = useVisitorMessages(visitorId);

  const onScrollToLower = () => {
    loadMore();
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    if (data?.data) {
      //@ts-ignore
      setList([...list, ...data.data]);
    }
  }, [data]);

  return (
    <PageCustom fullPage style={{ overflow: "hidden" }}>
      <NavBarNormal backText="访问详情"></NavBarNormal>
      {visitor ? <VisitorSummary data={visitor} /> : <></>}
      <View className="rounded-container-header"></View>
      <View className="flex-1 overflow-hidden">
        <ScrollView
          scrollY
          onScrollToLower={onScrollToLower}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View>
            <View className="flex flex-col gap-16 px-16">
              {list.map((message) => {
                return (
                  <>
                    <View className="text-12 text-gray-45 leading-20 text-center">
                      {message?.msgTime}
                    </View>
                    <ChatMessage
                      key={message.msgUk}
                      role={message.role}
                      text={message.content}
                    ></ChatMessage>
                  </>
                );
              })}
            </View>
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
};
