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

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

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

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

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

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

        <View className="my-learning-list">
          {items.map((item) => (
            <View
              key={item.id || item.content_id || item.title}
              className="my-learning-card"
              onClick={() => void Taro.navigateTo({ url: `/pages/content-detail/index?id=${item.id || item.content_id}` })}
            >
              <View className="my-learning-card__media">
                {item.image ? <Image className="my-learning-card__image" src={item.image} mode="aspectFill" /> : null}
              </View>
              <View className="my-learning-card__content">
                <Text className="my-learning-card__title">{item.title || "-"}</Text>
                <Text className="my-learning-card__meta">{item.date || item.viewed_at || "-"}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
