import { View, Text, Textarea, Button, Image, Video, Audio } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useEffect, useMemo, useState } from "react";
import AdminGuard from "../../components/AdminGuard";
import {
  approveReviewTask,
  getAdminReviewDetail,
  rejectReviewTask,
} from "../../api/admin";
import { useActionDrawer } from "../../components/action-drawer";
import { resolveMediaUrl } from "../../utils/media";
import "./index.scss";

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

const TARGET_LABELS: Record<string, string> = {
  id: "目标ID",
  type: "类型",
  postType: "互助类型",
  recordType: "记录类型",
  title: "标题",
  status: "状态",
  summary: "摘要",
  description: "正文/说明",
  sourceName: "来源",
  location: "地点",
  branchName: "所属组织",
  startsAt: "开始时间",
  endsAt: "结束时间",
  capacity: "容量",
  questionCount: "题目数",
  anonymous: "匿名",
  allowMultipleSubmit: "允许多次提交",
  memberCount: "服务人数",
  serviceTarget: "服务对象",
  tagsText: "标签",
  publisherTitle: "发布人身份",
  memberName: "会员",
  performedAt: "履职时间",
  mediaCount: "正文素材数",
  createdAt: "创建时间",
  updatedAt: "更新时间",
};

const TARGET_PRIORITY = [
  "id", "type", "postType", "recordType", "title", "status", "summary", "description",
  "sourceName", "location", "branchName", "startsAt", "endsAt", "capacity", "questionCount",
  "anonymous", "allowMultipleSubmit", "memberCount", "serviceTarget", "tagsText",
  "publisherTitle", "memberName", "performedAt", "mediaCount", "createdAt", "updatedAt",
];

function formatValue(value: unknown) {
  if (value === null || value === undefined || value === "") return "-";
  if (typeof value === "boolean") return value ? "是" : "否";
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

function targetRows(target: Record<string, unknown>) {
  return TARGET_PRIORITY
    .filter((key) => Object.prototype.hasOwnProperty.call(target, key))
    .map((key) => ({ label: TARGET_LABELS[key] || key, value: formatValue(target[key]) }));
}

function parseBodyBlocks(target: Record<string, any>): BodyBlock[] {
  if (Array.isArray(target?.bodyParsed)) return target.bodyParsed;
  if (Array.isArray(target?.bodyJson)) return target.bodyJson;
  if (Array.isArray(target?.body_json)) return target.body_json;
  const body = target?.body;
  if (Array.isArray(body)) return body;
  if (typeof body === "string" && body.trim()) {
    try {
      const parsed = JSON.parse(body);
      if (Array.isArray(parsed)) return parsed;
    } catch {
      return [{ type: "text", content: body }];
    }
  }
  const description = String(target?.description || "").trim();
  return description ? [{ type: "text", content: description }] : [];
}

function hasMediaBlock(blocks: BodyBlock[]) {
  return blocks.some((block) => ["image", "video", "audio"].includes(String(block?.type || "").toLowerCase()));
}

function mediaBlockFromRow(row: any): BodyBlock | null {
  const type = String(row?.mediaType || row?.media_type || row?.type || "").toLowerCase();
  if (!["image", "video", "audio"].includes(type)) return null;
  const role = String(row?.role || "").toLowerCase();
  if (row?.isCover === true || row?.is_cover === true || role === "cover") return null;
  const url = row?.originalUrl || row?.original_url || row?.url || row?.src;
  if (!url && !row?.fileId && !row?.file_id) return null;
  return {
    type,
    url,
    src: url,
    originalUrl: url,
    thumbnailUrl: row?.thumbnailUrl || row?.thumbnail_url,
    webpUrl: row?.webpUrl || row?.webp_url,
    poster: row?.poster || row?.coverUrl || row?.cover_url || row?.thumbnailUrl || row?.thumbnail_url,
    caption: row?.caption || row?.altText || row?.alt_text,
  };
}

function reviewBodyBlocks(target: Record<string, any>) {
  const parsed = parseBodyBlocks(target);
  const medias = Array.isArray(target?.medias)
    ? target.medias.map(mediaBlockFromRow).filter(Boolean) as BodyBlock[]
    : [];
  return medias.length > 0 && !hasMediaBlock(parsed) ? [...parsed, ...medias] : parsed;
}

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

function blockUrl(block: BodyBlock) {
  return resolveMediaUrl(String(block?.url || block?.src || block?.originalUrl || ""));
}

export default function AdminReviewDetailPage() {
  const router = useRouter();
  const id = Number(router.params.id);

  const [review, setReview] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [showRejectDrawer, setShowRejectDrawer] = useState(false);
  const [rejectReason, setRejectReason] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    getAdminReviewDetail(id)
      .then((data) => setReview(data))
      .catch(() => setReview(null))
      .finally(() => setLoading(false));
  }, [id]);

  const target = review?.target || {};
  const rows = useMemo(() => targetRows(target), [target]);
  const bodyBlocks = useMemo(() => reviewBodyBlocks(target), [target]);
  const coverUrl = resolveMediaUrl(String(target.coverImageUrl || target.coverUrl || ""));
  const canHandle = review?.status === "pending";

  const doApprove = async () => {
    if (submitting || !canHandle) return;
    const res = await showActionDrawer({
      type: "confirm",
      title: "通过审核",
      content: "请确认已查看详情和材料。",
      confirmText: "通过",
      cancelText: "取消"
    });
    if (!res.confirm) return;
    setSubmitting(true);
    try {
      await approveReviewTask(id, "审核通过");
      Taro.showToast({ title: "审核通过", icon: "none" });
      setTimeout(() => Taro.navigateBack(), 800);
    } catch {
      // toast already shown
    } finally {
      setSubmitting(false);
    }
  };

  const doReject = async () => {
    if (submitting || !canHandle) return;
    if (!rejectReason.trim()) {
      Taro.showToast({ title: "请填写驳回原因", icon: "none" });
      return;
    }
    setSubmitting(true);
    try {
      await rejectReviewTask(id, rejectReason.trim());
      Taro.showToast({ title: "已驳回", icon: "none" });
      setShowRejectDrawer(false);
      setTimeout(() => Taro.navigateBack(), 800);
    } catch {
      // toast already shown
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <AdminGuard>
        <View className="page-shell">
          <View className="page-body"><Text>加载中...</Text></View>
        </View>
      </AdminGuard>
    );
  }

  if (!review) {
    return (
      <AdminGuard>
        <View className="page-shell">
          <View className="page-body"><Text>审核任务不存在或已处理</Text></View>
        </View>
      </AdminGuard>
    );
  }

  return (
    <AdminGuard>
      <View className="page-shell admin-review-detail">
        <View className="page-body admin-review-detail__body">
          <View className="admin-review-detail__meta">
            <Text className="admin-review-detail__type">{review.type}</Text>
            <Text className={`admin-review-detail__status ${canHandle ? "is-pending" : ""}`}>
              {review.stage || "待审核"}
            </Text>
          </View>
          <Text className="admin-review-detail__title">{review.title}</Text>
          <View className="admin-review-detail__info">
            <Text>提交人：{review.submitterName || "-"}</Text>
            <Text>分会：{review.branchName || "-"}</Text>
            <Text>目标：{review.targetType || "-"} #{review.targetId || "-"}</Text>
            <Text>提交时间：{review.createdAt || "-"}</Text>
          </View>

          {coverUrl ? (
            <View className="admin-review-detail__cover">
              <Text className="admin-review-detail__section-title">封面图</Text>
              <Image className="admin-review-detail__cover-img" src={coverUrl} mode="widthFix" />
            </View>
          ) : null}

          {bodyBlocks.length ? (
            <View className="admin-review-detail__content">
              <Text className="admin-review-detail__section-title">正文预览</Text>
              <View className="admin-review-detail__rich-content">
                {bodyBlocks.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="admin-review-detail__body-block">
                        <Image className="admin-review-detail__body-image" src={src} mode="widthFix" />
                        {block.caption ? <Text className="admin-review-detail__caption">{block.caption}</Text> : null}
                      </View>
                    );
                  }
                  if (type === "video") {
                    const src = blockUrl(block);
                    if (!src) return null;
                    return (
                      <View key={`${type}-${index}`} className="admin-review-detail__body-block">
                        <Video className="admin-review-detail__body-video" src={src} poster={resolveMediaUrl(block.poster || block.coverUrl || block.thumbnailUrl || "")} controls />
                        {block.caption ? <Text className="admin-review-detail__caption">{block.caption}</Text> : null}
                      </View>
                    );
                  }
                  if (type === "audio") {
                    const src = blockUrl(block);
                    if (!src) return null;
                    return (
                      <View key={`${type}-${index}`} className="admin-review-detail__body-block">
                        <Audio className="admin-review-detail__body-audio" src={src} controls name={block.caption || review?.title || "音频"} />
                        {block.caption ? <Text className="admin-review-detail__caption">{block.caption}</Text> : null}
                      </View>
                    );
                  }
                  const text = blockText(block);
                  return text ? <Text key={`${type}-${index}`} className="admin-review-detail__body-text">{text}</Text> : null;
                })}
              </View>
            </View>
          ) : null}

          <View className="admin-review-detail__content">
            <Text className="admin-review-detail__section-title">目标内容</Text>
            <View className="admin-review-detail__target-list">
              {rows.length ? rows.map((row) => (
                <View key={row.label} className="admin-review-detail__target-row">
                  <Text className="admin-review-detail__target-label">{row.label}</Text>
                  <Text className="admin-review-detail__target-value">{row.value}</Text>
                </View>
              )) : (
                <Text className="admin-review-detail__empty">暂无目标详情</Text>
              )}
            </View>
          </View>

          {review.logs?.length ? (
            <View className="admin-review-detail__logs">
              <Text className="admin-review-detail__section-title">审核记录</Text>
              {review.logs.map((log: any, index: number) => (
                <View key={`${log.createdAt || index}_${index}`} className="admin-review-detail__log">
                  <Text>{log.createdAt || "-"}</Text>
                  <Text>{log.action || "-"}</Text>
                  <Text>{log.comment || ""}</Text>
                </View>
              ))}
            </View>
          ) : null}

          {canHandle ? (
            <View className="admin-review-detail__actions">
              <Button className="admin-review-detail__btn admin-review-detail__btn--approve" onClick={doApprove} disabled={submitting}>
                通过
              </Button>
              <Button className="admin-review-detail__btn admin-review-detail__btn--reject" onClick={() => setShowRejectDrawer(true)} disabled={submitting}>
                驳回
              </Button>
            </View>
          ) : null}
        </View>
        {showRejectDrawer ? (
          <View className="admin-reject-drawer">
            <View className="admin-reject-drawer__mask" onClick={() => setShowRejectDrawer(false)} />
            <View className="admin-reject-drawer__content">
              <View className="admin-reject-drawer__handle" />
              <Text className="admin-reject-drawer__title">驳回原因（必填）</Text>
              <Textarea
                className="admin-reject-drawer__textarea"
                value={rejectReason}
                maxlength={500}
                placeholder="请输入驳回原因，提交人会看到这条说明"
                onInput={(e) => setRejectReason(e.detail.value)}
              />
              <View className="admin-reject-drawer__btns">
                <Button className="admin-reject-drawer__btn admin-reject-drawer__btn--cancel" onClick={() => setShowRejectDrawer(false)}>
                  取消
                </Button>
                <Button className="admin-reject-drawer__btn admin-reject-drawer__btn--confirm" onClick={doReject} disabled={submitting}>
                  确认驳回
                </Button>
              </View>
            </View>
          </View>
        ) : null}
        {actionDrawer}
      </View>
    </AdminGuard>
  );
}
