import { View, ScrollView, Text } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/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 ChatRecordItem from "@/components/ChatRecordItem";
import { getVisitorInfo } from "@/service/visitor";
import { TSessionItem, TVisitorAgent, TVisitorMessage } from "@/types/visitor";
import VisitorSummary from "./components/VisitorSummary";

import { getVisitorSessions } from "@/service/visitor";

import style from "./index.module.less";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import EmptyData from "@/components/empty-data";

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

  const [visitor, setVisitor] = useState<TVisitorAgent>();
  
  const [totalCount, setTotalCount] = useState(1);

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

  const fetcher = async ([_url, {nextId, pageSize}]) => {
    const res = await getVisitorSessions({
      startId: nextId,
      pageSize,
      visitorId,
    });
    const _totalCount = res.data.totalCount;

    if (_totalCount && res.data.data) {
      setTotalCount(_totalCount);
      const data = res.data;
      data.data = data.data.map((item: TSessionItem) => {
        return { ...item, visitTimes: _totalCount - pageIndex };
      });
      return data;
    }

    const data = res.data;
    data.data = data.data.map((item: TSessionItem) => {
      return { ...item, visitTimes: totalCount - pageIndex };
    });

    return data;
  };



  const { list, pageIndex, loadMore } = useLoadMoreInfinite<TSessionItem[]>(
    createKey(`api/v1/my/visitor/sessions${visitorId}`, 5),
    fetcher);

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

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


  

  return (
    <PageCustom fullPage style={{ overflow: "hidden" }}>
      <NavBarNormal scrollFadeIn>访问详情</NavBarNormal>
      {visitor ? <VisitorSummary data={visitor} /> : <></>}
      <View className="rounded-container-header"></View>
      <View className="flex-1 overflow-hidden w-full">
        <ScrollView
          scrollY
          onScrollToLower={onScrollToLower}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View>
            <View className="flex flex-col gap-16 px-16 w-full">
              {list.length <= 0 && <View className="pt-100"><EmptyData type={'chat'} /></View>}
              {list.map((item) => {
                return (
                  <View className="w-full">
                    <View className="text-12 text-black leading-16">
                      {item?.msgTime.slice(0, 10)}
                    </View>
                    <View className="flex h-full w-full">
                      <View className="text-14 font-normal text-black leading-20 flex flex-col items-end">
                        <View>{item?.msgTime.slice(10, 16)} </View>
                      </View>
                      <View className="flex flex-1 w-full">
                        <View className={style.gutterLine}>
                          <View className={style.dot}></View>
                          <View className={style.line}></View>
                          <View className={style.dot}></View>
                        </View>
                        <View className="w-full h-full flex flex-col gap-8">
                          <View className="text-14 leading-24 text-title">
                            第{" "}
                            <Text className="text-primary">
                              {item?.visitTimes}
                            </Text>{" "}
                            次访问你的智能体
                          </View>
                          <View className="text-12 text-gray-45">
                            访问时长： {item.chatSecondsDesc}
                          </View>
                          <View className="text-12 text-gray-45">
                            共进行了 {item.chatRoundCnt} 轮对话{" "}
                          </View>
                          <ChatRecordItem
                            sessionId={item.sessionId}
                            visitorId={visitorId}
                            showMoreButton
                          ></ChatRecordItem>
                        </View>
                      </View>
                    </View>
                  </View>
                );
              })}
            </View>
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
};
