import { Image, RichText, Text, View } from "@tarojs/components";
import { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { getContentDetail } from "../../api/contents";
import { firstText } from "../../utils/media";
import "./index.scss";

function htmlFromDetail(detail: any) {
  const blocks = Array.isArray(detail?.bodyParsed) && detail.bodyParsed.length
    ? detail.bodyParsed
    : Array.isArray(detail?.blocks) ? detail.blocks : [];
  const htmlBlock = blocks.find((block: any) => block?.type === "html" && block?.content);
  return firstText(htmlBlock?.content, detail?.body, detail?.content);
}

export default function MemberDetailPage() {
  const { params } = useRouter();
  const id = Number(params?.id || params?.userId || 0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [detail, setDetail] = useState<any>(null);

  useDidShow(() => {
    if (!id) return;
    void (async () => {
      setLoading(true);
      try {
        const data = await getContentDetail(id);
        setDetail(data || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "会员风采加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const image = firstText(detail?.image, detail?.coverImageUrl, detail?.cover_image_url);
  const html = htmlFromDetail(detail);

  return (
    <View className="page-shell member-detail-page">
      <View className="page-body">
        {error ? (
          <View className="member-detail-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

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

        {!loading && !error && detail ? (
          <View className="card-surface member-detail-card">
            {image ? <Image className="member-detail-cover" src={image} mode="aspectFill" /> : null}

            <View className="member-detail-title">
              <Text className="member-detail-name">{detail.title || "会员风采"}</Text>
              <Text className="member-detail-meta">{detail.source || "会员风采"}</Text>
              <Text className="member-detail-meta">{String(detail.publishedAt || detail.published_at || detail.createdAt || detail.created_at || "-").slice(0, 10).replaceAll("-", ".")}</Text>
            </View>

            <View className="member-detail-section">
              <Text className="member-detail-label">风采简介</Text>
              <Text className="member-detail-text">{detail.summary || "暂无简介"}</Text>
            </View>

            {html ? (
              <View className="member-detail-section">
                <Text className="member-detail-label">详细内容</Text>
                <RichText className="member-detail-rich" nodes={html} />
              </View>
            ) : null}
          </View>
        ) : null}
      </View>
    </View>
  );
}
