import { Image, Text, View } from "@tarojs/components";
import Taro, { useReachBottom, usePullDownRefresh } from "@tarojs/taro";
import { useCallback } from "react";
import { getContents } from "../../api/contents";
import { useInfiniteList } from "../../hooks/useInfiniteList";
import "./index.scss";

export default function NewsListPage() {
  const fetcher = useCallback(
    (page: number, pageSize: number) =>
      getContents({ type: "news", page, pageSize }).then((data) => ({ items: Array.isArray(data) ? data : [] })),
    []
  );

  const { items, loading, loadingMore, hasMore, error, loadMore, refresh } = useInfiniteList<any>({
    fetcher,
    pageSize: 20,
  });

  useReachBottom(() => {
    if (hasMore && !loadingMore) void loadMore();
  });

  usePullDownRefresh(async () => {
    await refresh();
    Taro.stopPullDownRefresh();
  });

  return (
    <View className="news-list-page">
      <View className="news-list-page__body">
        {error ? (
          <View className="news-list-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading ? (
          <View className="news-list-state">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {!loading && !error && items.length === 0 ? (
          <View className="news-list-state">
            <Text>暂无新闻</Text>
          </View>
        ) : null}

        <View className="news-list-items">
          {items.map((item) => (
            <View key={item.id} className="news-list-card" onClick={() => void Taro.navigateTo({ url: `/pages/content-detail/index?id=${item.id}` })}>
              {item.coverImageUrl ? (
                <View className="news-list-card__media">
                  <Image className="news-list-card__image" src={item.coverImageUrl} mode="aspectFill" />
                </View>
              ) : null}
              <View className="news-list-card__content">
                <Text className="news-list-card__title">{item.title || "-"}</Text>
                <View className="news-list-card__meta">
                  <Text className="news-list-card__source">{item.sourceName || "-"}</Text>
                  <Text className="news-list-card__date">{String(item.published_at || item.created_at || "-").slice(0, 10).split("-").join(".")}</Text>
                </View>
              </View>
            </View>
          ))}
        </View>

        {loadingMore ? (
          <View className="news-list-state"><Text>加载更多...</Text></View>
        ) : !hasMore && items.length > 0 ? (
          <View className="news-list-state"><Text>已加载全部</Text></View>
        ) : null}
      </View>
    </View>
  );
}
