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

function bodyTextFrom(detail: any) {
  const blocks = Array.isArray(detail?.bodyParsed) ? detail.bodyParsed : [];
  const text = blocks
    .filter((block) => String(block?.type || "") === "text")
    .map((block) => String(block?.content || "").trim())
    .filter(Boolean)
    .join("\n");
  return text || String(detail?.content || detail?.body || "暂无内容");
}

function reviewReason(detail: any) {
  return String(detail?.reviewReason || detail?.review_reason || "").trim();
}

function canResubmit(detail: any) {
  return detail?.canResubmit === true || detail?.can_resubmit === true;
}

export default function SuggestionDetailPage() {
  useAuthGuard();
  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);
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

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

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

        <View className="suggestion-detail-header">
          <Text className="suggestion-detail-header__title">{detail?.title || "-"}</Text>
          <View className="suggestion-detail-header__meta">
            <Text>{detail?.statusText || detail?.status_text || detail?.status || "-"}</Text>
            <Text>{String(detail?.publishedAt || detail?.published_at || detail?.createdAt || detail?.created_at || "-").slice(0, 10).replaceAll("-", ".")}</Text>
          </View>
        </View>

        <View className="suggestion-detail-card">
          <Text className="suggestion-detail-card__body">{bodyTextFrom(detail)}</Text>
        </View>

        {reviewReason(detail) ? (
          <View className="suggestion-detail-reason">
            <Text>驳回原因：{reviewReason(detail)}</Text>
          </View>
        ) : null}

        {canResubmit(detail) ? (
          <Button className="suggestion-detail-edit" onClick={() => void Taro.navigateTo({ url: `/pages/suggestion-create/index?id=${id}` })}>
            修改后重提
          </Button>
        ) : null}
      </View>
    </View>
  );
}
