import { Text, View } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import { useState } from "react";
import {
  acceptMutualAidContactRequest,
  getMutualAidDetail,
  rejectMutualAidContactRequest,
  requestMutualAidContact,
  type MutualAidContactRequest
} from "../../api/mutual-aid";
import { useActionDrawer } from "../../components/action-drawer";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { ensureMemberAccess } from "../../utils/permission";
import "./index.scss";

function statusText(raw?: string, text?: string) {
  if (text) return text;
  switch (raw) {
    case "published":
      return "已发布";
    case "draft":
    case "pending":
    case "pending_branch_review":
    case "pending_city_review":
      return "审核中";
    case "rejected":
    case "branch_rejected":
    case "city_rejected":
      return "已驳回";
    default:
      return raw || "-";
  }
}

function normalizeTags(item: any) {
  if (Array.isArray(item?.tags) && item.tags.length > 0) return item.tags;
  const text = String(item?.tagsText || item?.tags_text || "").trim();
  if (!text) return [];
  return text
    .split(/[、，,]/)
    .map((v) => v.trim())
    .filter(Boolean);
}

export default function MutualAidDetailPage() {
  useAuthGuard();
  const [loading, setLoading] = useState(true);
  const [doing, setDoing] = useState("");
  const [error, setError] = useState("");
  const [detail, setDetail] = useState<any>(null);
  const [postId, setPostId] = useState(0);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const loadDetail = async (id: number) => {
    setLoading(true);
    try {
      const data = await getMutualAidDetail(id);
      setDetail(data);
      setError("");
    } catch (e: any) {
      setError(e?.message || "加载失败");
    } finally {
      setLoading(false);
    }
  };

  useLoad((params) => {
    const id = Number(params?.id || 0);
    setPostId(id);
    if (!id) {
      setError("参数错误");
      setLoading(false);
      return;
    }

    void loadDetail(id);
  });

  const rejected = ["rejected", "branch_rejected", "city_rejected"].includes(String(detail?.status || ""));
  const reviewReason = detail?.review_reason || detail?.reviewReason || "";

  const gotoEditResubmit = () => {
    const id = Number(detail?.id || 0);
    if (!id) return;
    const postType = String(detail?.post_type || detail?.postType || "");
    if (postType === "need") {
      void Taro.navigateTo({ url: `/pages/demand-create/index?id=${id}&mode=edit-resubmit` });
      return;
    }
    void Taro.navigateTo({ url: `/pages/mutual-aid-create/index?id=${id}&mode=edit-resubmit` });
  };

  const onRequestContact = async () => {
    const id = Number(detail?.id || postId || 0);
    if (!id || doing) return;
    const ok = await ensureMemberAccess("仅会员可申请互助对接");
    if (!ok) return;
    const confirm = await showActionDrawer({
      type: "confirm",
      title: "申请对接",
      content: "提交后发布人可看到你的对接请求，同意后你将看到联系方式。",
      confirmText: "提交申请",
      cancelText: "取消"
    });
    if (!confirm.confirm) return;
    setDoing("request");
    try {
      await requestMutualAidContact(id);
      Taro.showToast({ title: "申请已提交", icon: "none" });
      await loadDetail(id);
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "提交失败", icon: "none" });
    } finally {
      setDoing("");
    }
  };

  const onDecideRequest = async (request: MutualAidContactRequest, accept: boolean) => {
    const requestId = Number(request?.id || 0);
    const id = Number(detail?.id || postId || 0);
    if (!requestId || !id || doing) return;
    const ok = await ensureMemberAccess("仅会员可处理互助对接");
    if (!ok) return;
    const confirm = await showActionDrawer({
      type: accept ? "confirm" : "danger",
      title: accept ? "同意对接" : "拒绝对接",
      content: accept ? "同意后申请人可查看你的联系方式。" : "确认拒绝这条对接申请？",
      confirmText: accept ? "同意" : "拒绝",
      cancelText: "取消",
      confirmTone: accept ? "primary" : "danger"
    });
    if (!confirm.confirm) return;
    setDoing(`${accept ? "accept" : "reject"}-${requestId}`);
    try {
      if (accept) await acceptMutualAidContactRequest(requestId);
      else await rejectMutualAidContactRequest(requestId);
      Taro.showToast({ title: accept ? "已同意" : "已拒绝", icon: "none" });
      await loadDetail(id);
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "操作失败", icon: "none" });
    } finally {
      setDoing("");
    }
  };

  const contactVisible = Boolean(detail?.contactVisible ?? detail?.contact_visible);
  const contactStatus = String(detail?.contactRequestStatus || detail?.contact_request_status || "");
  const contactRequests = (Array.isArray(detail?.contactRequests) ? detail.contactRequests : []) as MutualAidContactRequest[];
  const contactPhone = detail?.contactPhone || detail?.contact_phone || "";
  const contactWechat = detail?.contactWechat || detail?.contact_wechat || "";
  const tags = normalizeTags(detail || {});
  const publisherName =
    detail?.publisherName ||
    detail?.publisher_name ||
    detail?.author ||
    detail?.publisherTitle ||
    detail?.publisher_title ||
    "-";

  return (
    <View className="page-shell mutual-aid-detail-page">
      <View className="page-body">
        {loading ? <Text className="state-text">加载中...</Text> : null}
        {!loading && error ? <Text className="state-text state-error">{error}</Text> : null}
        {!loading && !error && detail ? (
          <View className="card-surface detail-card">
            <View className="detail-head">
              <Text className="detail-title">{detail.title || "未命名互助"}</Text>
              <Text className="detail-status">{statusText(detail.status, detail.statusText || detail.status_text)}</Text>
            </View>
            {tags.length > 0 ? (
              <View className="detail-tags">
                {tags.map((tag) => (
                  <Text key={tag} className="detail-tag">
                    {tag}
                  </Text>
                ))}
              </View>
            ) : null}
            <View className="detail-publisher">
              <View className="detail-publisher__avatar">人</View>
              <Text className="detail-meta">发布人：{publisherName}</Text>
            </View>
            {rejected ? <Text className="detail-meta">驳回原因：{reviewReason || "暂无驳回说明"}</Text> : null}
            <Text className="detail-content">{detail.content || detail.description || "暂无详情内容"}</Text>

            {contactVisible ? (
              <View className="detail-contact">
                <Text className="detail-contact__title">联系方式</Text>
                <Text className="detail-contact__line">电话：{contactPhone || "-"}</Text>
                <Text className="detail-contact__line">微信：{contactWechat || "-"}</Text>
              </View>
            ) : null}

            {!contactVisible && !rejected && String(detail.status || "") === "published" ? (
              <View className="detail-contact detail-contact--soft">
                <Text className="detail-contact__title">互助对接</Text>
                <Text className="detail-contact__line">
                  {contactStatus === "pending"
                    ? "你的对接申请已提交，等待发布人确认。"
                    : contactStatus === "rejected"
                      ? "发布人暂未同意本次对接，可重新提交申请。"
                      : "申请对接后，发布人同意才会显示联系方式。"}
                </Text>
                {contactRequests.length === 0 ? (
                  <View
                    className={`detail-main-action ${doing === "request" || contactStatus === "pending" ? "is-disabled" : ""}`}
                    onClick={() => {
                      if (contactStatus !== "pending") void onRequestContact();
                    }}
                  >
                    <Text>{contactStatus === "pending" ? "等待确认" : "申请对接"}</Text>
                  </View>
                ) : null}
              </View>
            ) : null}

            {contactRequests.length > 0 ? (
              <View className="detail-contact-requests">
                <Text className="detail-contact__title">对接申请</Text>
                {contactRequests.map((request) => {
                  const status = String(request.status || "");
                  const requester = request.requester_name || request.requesterName || "申请人";
                  return (
                    <View key={request.id} className="detail-request-card">
                      <View className="detail-request-card__head">
                        <Text className="detail-request-card__name">{requester}</Text>
                        <Text className={`detail-request-card__status ${status}`}>{status === "accepted" ? "已同意" : status === "rejected" ? "已拒绝" : "待处理"}</Text>
                      </View>
                      <Text className="detail-request-card__meta">电话：{request.requester_phone || request.requesterPhone || "-"}</Text>
                      {request.message ? <Text className="detail-request-card__meta">留言：{request.message}</Text> : null}
                      {status === "pending" ? (
                        <View className="detail-request-card__actions">
                          <View className="detail-request-card__btn ghost" onClick={() => void onDecideRequest(request, false)}>
                            <Text>拒绝</Text>
                          </View>
                          <View className="detail-request-card__btn" onClick={() => void onDecideRequest(request, true)}>
                            <Text>同意</Text>
                          </View>
                        </View>
                      ) : null}
                    </View>
                  );
                })}
              </View>
            ) : null}

            <View className="detail-actions">
              {rejected ? (
                <View className="detail-btn" style={{ marginRight: "12rpx" }} onClick={() => gotoEditResubmit()}>
                  <Text>修改后重新提交</Text>
                </View>
              ) : null}
              <View className="detail-btn" onClick={() => Taro.navigateBack()}>
                <Text>返回</Text>
              </View>
            </View>
          </View>
        ) : null}
      </View>
      {actionDrawer}
    </View>
  );
}
