import {useState, useCallback, useEffect} from 'react'
import {View, Text} from '@tarojs/components'
import Taro from '@tarojs/taro'
import {Loading, InfiniteLoading, Empty, Space, Tag} from '@nutui/nutui-react-taro'
import {pageShopChatConversation} from "@/api/shop/shopChatConversation";
import FixedButton from "@/components/FixedButton";

const Index = () => {
  const [list, setList] = useState<any[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // 获取消息数据
  const fetchMessageData = useCallback(async (resetPage = false, targetPage?: number, searchKeyword?: string) => {
    setLoading(true);
    try {
      const currentPage = resetPage ? 1 : (targetPage || page);

      // 构建API参数，根据状态筛选
      const params: any = {
        page: currentPage
      };

      // 添加搜索关键词
      if (searchKeyword && searchKeyword.trim()) {
        params.keywords = searchKeyword.trim();
      }

      const res = await pageShopChatConversation(params);

      if (res?.list && res.list.length > 0) {
        // 正确映射状态
        const mappedList = res.list.map(customer => ({
          ...customer
        }));

        // 如果是重置页面或第一页，直接设置新数据；否则追加数据
        if (resetPage || currentPage === 1) {
          setList(mappedList);
        } else {
          setList(prevList => prevList.concat(mappedList));
        }

        // 正确判断是否还有更多数据
        const hasMoreData = res.list.length >= 10; // 假设每页10条数据
        setHasMore(hasMoreData);
      } else {
        if (resetPage || currentPage === 1) {
          setList([]);
        }
        setHasMore(false);
      }

      setPage(currentPage);
    } catch (error) {
      console.error('获取消息数据失败:', error);
      Taro.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  }, [page]);

  const reloadMore = async () => {
    if (loading || !hasMore) return; // 防止重复加载
    const nextPage = page + 1;
    await fetchMessageData(false, nextPage);
  }


  // 获取列表数据（现在使用服务端搜索，不需要消息端过滤）
  const getFilteredList = () => {
    return list;
  };

  useEffect(() => {
    // 初始化时加载数据
    fetchMessageData(true, 1, '');
  }, []);

  // 渲染消息项
  const renderMessageItem = (customer: any) => (
    <View key={customer.userId} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex items-center">
        <View className="flex-1">
          <View className="flex items-center justify-between mb-1">
            <Text className="font-semibold text-gray-800 mr-2">
              关于XXXX的通知
            </Text>
            <Tag type={'warning'}>未读</Tag>
            {/*<Tag type={'success'}>已读</Tag>*/}
          </View>
          <Space direction={'vertical'}>
            {/*<Text className="text-xs text-gray-500">统一代码：{customer.dealerCode}</Text>*/}
            <Text className="text-xs text-gray-500">
              创建时间：{customer.createTime}
            </Text>
          </Space>
        </View>
      </View>
    </View>
  );

  // 渲染消息列表
  const renderMessageList = () => {
    const filteredList = getFilteredList();

    return (
      <View className="p-4" style={{
        height: '90vh',
        overflowY: 'auto',
        overflowX: 'hidden'
      }}>
        <InfiniteLoading
          target="scroll"
          hasMore={hasMore}
          onLoadMore={reloadMore}
          onScroll={() => {
            // 滚动事件处理
          }}
          onScrollToUpper={() => {
            // 滚动到顶部事件处理
          }}
          loadingText={
            <>
              加载中...
            </>
          }
          loadMoreText={
            filteredList.length === 0 ? (
              <Empty
                style={{backgroundColor: 'transparent'}}
                description={loading ? "加载中..." : "暂无消息数据"}
              />
            ) : (
              <View className={'h-12 flex items-center justify-center'}>
                <Text className="text-gray-500 text-sm">没有更多了</Text>
              </View>
            )
          }
        >
          {loading && filteredList.length === 0 ? (
            <View className="flex items-center justify-center py-8">
              <Loading/>
              <Text className="text-gray-500 mt-2 ml-2">加载中...</Text>
            </View>
          ) : (
            filteredList.map(renderMessageItem)
          )}
        </InfiniteLoading>
      </View>
    );
  };

  return (
    <View className="min-h-screen bg-gray-50">
      {/* 消息列表 */}
      {renderMessageList()}
      <FixedButton />
    </View>
  );
};

export default Index;
