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

const TABS = [
  { key: "", label: "全部" },
  { key: "历史文化", label: "历史文化" },
  { key: "法律解读", label: "法律解读" },
  { key: "统战历史", label: "统战历史" }
];

export default function LearningListPage() {
  const [tab, setTab] = useState("");

  const fetcher = useCallback(
    (page: number, pageSize: number) =>
      getContents({ type: "learning", sourceName: tab, page, pageSize }).then((data) => ({ items: Array.isArray(data) ? data : [] })),
    [tab]
  );

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

  const onTab = async (next: string) => {
    if (next === tab) return;
    setTab(next);
  };

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

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

  return (
    <View className="learning-list-page">
      <View className="learning-list-page__body">
        <View className="learning-list-tabs">
          {TABS.map((item) => (
            <View key={item.label} className={"learning-list-tabs__item " + (tab === item.key ? "is-active" : "")} onClick={() => void onTab(item.key)}>
              <Text>{item.label}</Text>
            </View>
          ))}
        </View>

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

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

        {!loading && !error && items.length === 0 ? (
          <View className="learning-list-state"><Text>暂无学习内容</Text></View>
        ) : null}

        <View className="learning-list-items">
          {items.map((item) => {
            const learningUserCount =
              item.learning_user_count !== undefined && item.learning_user_count !== null
                ? Number(item.learning_user_count) || 0
                : Number(item.view_count) || 0;
            return (
              <View key={item.id} className="learning-list-card" onClick={() => void Taro.navigateTo({ url: "/pages/content-detail/index?id=" + item.id })}>
                {item.coverImageUrl ? (
                  <View className="learning-list-card__media">
                    <Image className="learning-list-card__image" src={item.coverImageUrl} mode="aspectFill" />
                  </View>
                ) : null}
                <View className="learning-list-card__content">
                  <Text className="learning-list-card__title">{item.title || "-"}</Text>
                  <View className="learning-list-card__meta">
                    <Text>{item.sourceName || "-"}</Text>
                    <Text>{"学习用户：" + learningUserCount + "人"}</Text>
                  </View>
                </View>
              </View>
            );
          })}
        </View>

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