import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getMyBrowsingHistory } from "../../api/me";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import "./index.scss";

function routeToDetail(path?: string) {
  if (!path) return "";
  const contentId = path.split("/").pop();
  if (!contentId) return "";
  return `/pages/content-detail/index?id=${contentId}`;
}

function typeText(type?: string) {
  if (type === "learning") return "学习园地";
  return "新闻资讯";
}

export default function MyBrowsingHistoryPage() {
  useAuthGuard();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const data = await getMyBrowsingHistory();
        setItems(Array.isArray(data) ? data : []);
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

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

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

        {!loading && !error && items.length === 0 ? (
          <View className="my-browsing-state">
            <Text>暂无浏览历史</Text>
          </View>
        ) : null}

        <View className="my-browsing-list">
          {items.map((item) => (
            <View
              key={`${item.type}-${item.id}`}
              className="my-browsing-card"
              onClick={() => {
                const target = routeToDetail(item.targetPath);
                if (target) void Taro.navigateTo({ url: target });
              }}
            >
              <View className="my-browsing-card__media">
                {item.coverImageUrl ? <Image className="my-browsing-card__image" src={item.coverImageUrl} mode="aspectFill" /> : null}
              </View>
              <View className="my-browsing-card__content">
                <Text className="my-browsing-card__title">{item.title || "-"}</Text>
                <View className="my-browsing-card__row">
                  <Text className="my-browsing-card__type">{typeText(item.type)}</Text>
                  <Text className="my-browsing-card__date">{item.date || "-"}</Text>
                </View>
                <Text className="my-browsing-card__source">{item.source || "-"}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
