import { View, Image, Text } from "@tarojs/components";
import Taro, { useReachBottom, useRouter } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/index";
import PageCustom from "@/components/page-custom/index";
import { useEffect, useState } from "react";
import { isSuccess } from "@/utils";
import { getVisitorInfo } from "@/service/visitor";
import VisitorSummary from "./components/VisitorSummary";

import { getVisitorMessages } from "@/service/visitor";
import { TSessionItem, TVisitorAgent, TVisitorChat } from "@/types/visitor";
import { useLoadMore } from "@/utils/loadMore";
import IconEditButtonBlue from "@/images/svgs/dashboard/IconEditButtonBlue.svg";
import style from "./index.module.less";

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

  const [visitor, setVisitor] = useState<TVisitorAgent>();
  const [list, setList] = useState<TVisitorChat[]>([]);

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

  const fetcher = async ([_url, nextId, page, pageSize, sessionId]) => {
    const res = await getVisitorMessages({
      startId: nextId,
      pageSize,
      visitorId,
      sessionId,
    });
    return res.data;
  };

  const { data, loadMore } = useLoadMore<{
    data?: TVisitorChat[];
    nextId?: string;
    totalCount?: number;
  }>({
    url: `api/v1/my/visitor/sessions${visitorId}`,
    fetcher,
    params: [sessionId],
  });

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

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

  useReachBottom(() => {
    loadMore();
  });

  const renderContent = (item: TVisitorChat) => {
    if (item.role === "user") {
      return <View className="text-14 text-title mb-8">{item?.content}</View>;
    }

    return (
      <View
        className="p-16 text-title rounded-8 relative"
        style={{ backgroundColor: "#F4F9FF" }}
      >
        <View>{item.content}</View>
        <View className={style.editButton}>
          <Image src={IconEditButtonBlue} className="w-14 h-14" />
        </View>
      </View>
    );
  };

  return (
    <PageCustom>
      <NavBarNormal backText="返回" scrollFadeIn></NavBarNormal>
      {visitor ? <VisitorSummary data={visitor} /> : <></>}
      <View className="flex-1 overflow-hidden w-full mb-100">
        <View className="flex flex-col gap-16 px-16 w-full">
          {list.map((item) => {
            return (
              <View className={` bg-white rounded-12 overflow-hidden`}>
                <View className="p-16">{renderContent(item)}</View>
              </View>
            );
          })}
        </View>
      </View>
    </PageCustom>
  );
};
