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

type BodyBlock = {
  type?: string;
  content?: string;
  text?: string;
  url?: string;
  src?: string;
  originalUrl?: string;
  poster?: string;
  coverUrl?: string;
  thumbnailUrl?: string;
  caption?: string;
};

function parseBodyBlocks(detail: any): BodyBlock[] {
  const parsed = detail?.bodyParsed || detail?.blocks;
  if (Array.isArray(parsed)) return parsed;
  if (Array.isArray(detail?.bodyJson)) return detail.bodyJson;
  if (Array.isArray(detail?.body_json)) return detail.body_json;
  const body = detail?.body;
  if (Array.isArray(body)) return body;
  if (typeof body === "string" && body.trim()) {
    try {
      const json = JSON.parse(body);
      if (Array.isArray(json)) return json;
    } catch {
      // Fall through to plain text rendering.
    }
    return [{ type: "text", content: body }];
  }
  const summary = typeof detail?.summary === "string" ? detail.summary.trim() : "";
  return [{ type: "text", content: summary || "暂无内容" }];
}

function blockText(block: BodyBlock) {
  return String(block?.content ?? block?.text ?? "");
}

function blockUrl(block: BodyBlock) {
  return resolveMediaUrl(firstText(block?.url, block?.src, block?.originalUrl, block?.thumbnailUrl));
}

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

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

  const coverImageUrl = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.image, detail?.image_url));
  const showHero = !!coverImageUrl;
  const blocks = parseBodyBlocks(detail);
  const publishedDate = String(detail?.publishedAt || detail?.published_at || detail?.createdAt || detail?.created_at || "")
    .slice(0, 10)
    .split("-")
    .join(".");

  return (
    <View className="content-detail-page">
      {showHero ? (
        <View className="content-detail-hero">
          <Image className="content-detail-hero__image" src={coverImageUrl} mode="aspectFill" />
          <View className="content-detail-hero__mask" />
        </View>
      ) : null}

      <View className={`content-detail-page__body ${showHero ? "is-floating" : ""}`}>
        {error ? (
          <View className="content-detail-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

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

        <View className="content-detail-header">
          <Text className="content-detail-header__title">{detail?.title || "-"}</Text>
          <View className="content-detail-header__meta">
            <Text>{detail?.sourceName || "-"}</Text>
            <Text>{publishedDate || "-"}</Text>
          </View>
        </View>

        <View className="content-detail-card">
          {blocks.map((block, index) => {
            const type = String(block?.type || "text").toLowerCase();
            if (type === "image") {
              const src = blockUrl(block);
              if (!src) return null;
              return (
                <View key={`${type}-${index}`} className="content-detail-block content-detail-block--image">
                  <Image className="content-detail-block__image" src={src} mode="widthFix" />
                  {block.caption ? <Text className="content-detail-block__caption">{block.caption}</Text> : null}
                </View>
              );
            }
            if (type === "video") {
              const src = blockUrl(block);
              if (!src) return null;
              const poster = resolveMediaUrl(firstText(block.poster, block.coverUrl, block.thumbnailUrl));
              return (
                <View key={`${type}-${index}`} className="content-detail-block content-detail-block--video">
                  <Video className="content-detail-block__video" src={src} poster={poster} controls />
                  {block.caption ? <Text className="content-detail-block__caption">{block.caption}</Text> : null}
                </View>
              );
            }
            if (type === "audio") {
              const src = blockUrl(block);
              if (!src) return null;
              return (
                <View key={`${type}-${index}`} className="content-detail-block content-detail-block--audio">
                  <Audio className="content-detail-block__audio" src={src} controls name={block.caption || detail?.title || "音频"} />
                  {block.caption ? <Text className="content-detail-block__caption">{block.caption}</Text> : null}
                </View>
              );
            }
            if (type === "html") {
              return (
                <View key={`${type}-${index}`} className="content-detail-block content-detail-block--html">
                  <RichText nodes={blockText(block)} />
                </View>
              );
            }
            return (
              <Text key={`${type}-${index}`} className="content-detail-card__body">
                {blockText(block)}
              </Text>
            );
          })}
        </View>
      </View>
    </View>
  );
}
