import { RichText, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getContentDetail, getContents } from "../../api/contents";
import "./index.scss";

function blocksOf(detail: any) {
  const blocks = detail?.bodyParsed || detail?.blocks || detail?.bodyJson || detail?.body_json;
  if (Array.isArray(blocks)) return blocks;
  const body = String(detail?.body || detail?.summary || "").trim();
  return body ? [{ type: body.includes("<") ? "html" : "text", content: body }] : [];
}

export default function AboutIntroPage() {
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const rows = await getContents({ type: "about_intro", page: 1, pageSize: 1 });
        const first = Array.isArray(rows) ? rows[0] : null;
        const full = first?.id ? await getContentDetail(first.id) : null;
        setDetail(full || first || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "关于新联会加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const blocks = blocksOf(detail);

  return (
    <View className="about-page">
      <View className="about-page__body">
        {error ? <Text className="about-state is-error">{error}</Text> : null}
        {loading ? <Text className="about-state">加载中...</Text> : null}
        <View className="about-panel">
          <Text className="about-title">{detail?.title || "关于大连市新联会"}</Text>
          {detail?.summary ? <Text className="about-summary">{detail.summary}</Text> : null}
          {blocks.length ? (
            blocks.map((block: any, index: number) => {
              const type = String(block?.type || "text").toLowerCase();
              const content = String(block?.content || block?.text || "");
              return type === "html" ? (
                <View key={index} className="about-rich">
                  <RichText nodes={content} />
                </View>
              ) : (
                <Text key={index} className="about-paragraph">{content}</Text>
              );
            })
          ) : (
            <Text className="about-paragraph">大连市新的社会阶层人士联谊会是联系和服务新的社会阶层人士的重要平台。</Text>
          )}
          <View className="about-actions">
            <View className="about-action" onClick={() => Taro.navigateTo({ url: "/pages/about-structure/index" })}>
              <Text>查看组织架构</Text>
            </View>
          </View>
        </View>
      </View>
    </View>
  );
}
