import { Text, View, ScrollView } from "@tarojs/components";
import {
  useLoad,
  setNavigationBarTitle,
  navigateTo,
  navigateBack,
} from "@tarojs/taro";
import { timeFormat } from "../../../utils";
import { Image, NavBar } from "@nutui/nutui-react-taro";
import { ArrowLeft, Message } from "@nutui/icons-react-taro";
import { useEffect, useState } from "react";
import CommentInput from "../../../components/comment-list/comment-input";
import {
  getNotificationListApi,
  markAsReadByTypeApi,
} from "../../../api/notifications";
import "./index.scss";
const MessageList = () => {
  const [showCommentInput, setShowCommentInput] = useState(false);
  const [notificationList, setNotificationList] = useState<any[]>([]);
  const [CommentPostId, setCommentPostId] = useState(0);
  const [CommentParentCommentId, setCommentParentCommentId] = useState(0);
  const [typeId, setTypeId] = useState("");
  const [title, setTitle] = useState("");

  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  useLoad((options) => {
    switch (options.type) {
      case "like":
        setTypeId("4,5");
        handleReadNotification("4,5");
        setTitle("收到的点赞");
        setNavigationBarTitle({
          title: "收到的点赞",
        });
        break;
      case "comment":
        setTypeId("1,2,3");
        handleReadNotification("1,2,3");
        setTitle("评论和@");
        setNavigationBarTitle({
          title: "评论和@",
        });
        break;
      case "follow":
        setTypeId("6,7");
        handleReadNotification("6,7");
        setTitle("关注和分享");
        setNavigationBarTitle({
          title: "关注和分享",
        });
        break;

      default:
        break;
    }
  });

  // 标记消息类型通知为已读
  const handleReadNotification = async (type_id) => {
    markAsReadByTypeApi({ type_id });
  };

  const getNotificationList = async (page = 1, isRefresh = false) => {
    if (loading) return;

    setLoading(true);
    try {
      const res: any = await getNotificationListApi({
        type_id: typeId,
        page: page,
        limit: 10,
      });

      if (res.code === 200) {
        const { list, has_more } = res.data;
        console.log("API response:", {
          page,
          listLength: list.length,
          has_more,
          totalCount: res.data.count,
        });

        if (isRefresh || page === 1) {
          // 刷新或首次加载，替换数据
          setNotificationList(list);
        } else {
          // 加载更多，追加数据
          setNotificationList((prev) => [...prev, ...list]);
        }

        setCurrentPage(page);
        setHasMore(has_more);
        console.log("Updated state:", { currentPage: page, hasMore: has_more });
      }
    } catch (error) {
      console.error("获取通知列表失败:", error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };
  // 加载更多数据
  const loadMore = () => {
    console.log("loadMore triggered:", { hasMore, loading, currentPage });
    if (hasMore && !loading) {
      console.log("Loading next page:", currentPage + 1);
      getNotificationList(currentPage + 1, false);
    }
  };

  // 下拉刷新
  const onRefresh = () => {
    setRefreshing(true);
    setCurrentPage(1);
    setHasMore(true);
    getNotificationList(1, true);
  };

  useEffect(() => {
    // 重置分页状态
    if (typeId) {
      setCurrentPage(1);
      setHasMore(true);
      setNotificationList([]);
      getNotificationList(1, true);
    }
  }, [typeId]);
  return (
    <>
      <NavBar
        back={
          <>
            <ArrowLeft />
            返回
          </>
        }
        onBackClick={(e) => {
          e.preventDefault();
          navigateBack({ delta: 1 });
        }}
      >
        {title}
      </NavBar>
      <ScrollView
        className="bg-[#f8f8f8] message-list"
        scrollY
        refresherEnabled
        refresherTriggered={refreshing}
        onRefresherRefresh={onRefresh}
        onScrollToLower={loadMore}
        lowerThreshold={50}
        enhanced
        showScrollbar={false}
      >
        {notificationList.map((item, index) => {
          return (
            <>
              <View
                key={item.id || index}
                className="p-[10px] text-[14px] flex mb-[2px] bg-[#fff]"
              >
                <View className="w-[50px] h-[50px] bg-[#000] rounded-[50%] overflow-hidden">
                  <Image
                    width={50}
                    height={50}
                    src="https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg"
                    mode="aspectFill"
                  />
                </View>
                <View className="flex-1 ml-[10px]">
                  <View className="text-[14px] font-[800] mb-[3px]">
                    {item.nickname || item.username}
                  </View>
                  <View className="text-[12px] text-[#949494] mb-[3px]">
                    {timeFormat(item.created_at)}
                  </View>
                  <View className="text-[14px] text-[#3d3d3d]">
                    {item.type_id === 4 ? "点赞了你的动态" : ""}
                    {item.type_id === 5 ? "点赞了你的评论" : ""}
                    {item.type_id === 2 ? "评论了你的动态" : ""}
                    {item.type_id === 3 ? item.reply_comment_info.content : ""}
                    {item.type_id === 1
                      ? `${
                          item.source_type === "post" ? "在动态中" : "在评论中"
                        }刚刚@了你 `
                      : ""}
                    {item.type_id === 6 ? "关注了你" : ""}
                    {item.type_id === 7 ? "分享了你的动态" : ""}
                  </View>

                  <View
                    className="text-[#858585] text-[14px] pl-[5px] mt-[10px]"
                    style={{ borderLeft: "4rpx solid #e2e2e2" }}
                  >
                    {item.source_type === "comment"
                      ? item.sourse_info.content
                      : ""}
                    {item.source_type === "post" && item.type_id === 2
                      ? item.reply_comment_info.content
                      : ""}
                  </View>
                  {/* 回复/评论 */}
                  {item.type_id === 2 ||
                  item.type_id === 3 ||
                  (item.type_id === 1 && item.source_type === "comment") ? (
                    <View
                      className="flex mt-[10px]"
                      onClick={() => {
                        setShowCommentInput(true);
                        setCommentPostId(item.source_post_info.id);
                        setCommentParentCommentId(item.reply_comment_info.id);
                      }}
                    >
                      <View className="pt-[5px] pb-[5px] pl-[10px] pr-[10px] bg-[#f8f8f8] flex items-center rounded-[20px]">
                        <Message size={16} color="#949494" />
                        <Text className="text-[12px] ml-[5px]">回复</Text>
                      </View>
                    </View>
                  ) : (
                    <></>
                  )}
                </View>
                {item.source_post_info ? (
                  <View
                    className="text-[12px] text-[#333]"
                    onClick={() => {
                      navigateTo({
                        url: `/pages/detail/index?id=${item.source_post_info.id}`,
                      });
                    }}
                  >
                    <Image
                      width={50}
                      height={50}
                      src={
                        item.source_post_info.media_url
                          ? item.source_post_info.media_url.split(",")[0]
                          : ""
                      }
                      mode="aspectFill"
                    />
                  </View>
                ) : (
                  <></>
                )}
              </View>
            </>
          );
        })}

        {/* 加载更多按钮 - 用于测试 */}
        {hasMore && !loading && (
          <View className="flex justify-center items-center py-[20px]">
            <View
              className="px-[20px] py-[10px] bg-[#007aff] rounded-[20px]"
              onClick={loadMore}
            >
              <Text className="text-[14px] text-white">加载更多</Text>
            </View>
          </View>
        )}

        {/* 加载指示器 */}
        {loading && (
          <View className="flex justify-center items-center py-[20px]">
            <Text className="text-[14px] text-[#999]">加载中...</Text>
          </View>
        )}

        {/* 无更多数据提示 */}
        {!hasMore && notificationList.length > 0 && (
          <View className="flex justify-center items-center py-[20px]">
            <Text className="text-[14px] text-[#999]">没有更多数据了</Text>
          </View>
        )}

        {/* 空状态 */}
        {!loading && notificationList.length === 0 && (
          <View className="flex justify-center items-center py-[100px]">
            <Text className="text-[14px] text-[#999]">暂无消息</Text>
          </View>
        )}

        {showCommentInput ? (
          <CommentInput
            postId={CommentPostId}
            parentCommentId={CommentParentCommentId}
            onClose={() => setShowCommentInput(false)}
            onOK={() => {
              setShowCommentInput(false);
              getNotificationList();
            }}
          />
        ) : null}
      </ScrollView>
    </>
  );
};

export default MessageList;
