import { Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { getMyProfile } from "../../api/me";
import { getMutualAidPosts } from "../../api/mutual-aid";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { useActionDrawer } from "../../components/action-drawer";
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 isRejected(status?: string) {
  return ["rejected", "branch_rejected", "city_rejected"].includes(String(status || ""));
}

export default function MyMutualAidResourcesPage() {
  useAuthGuard();
  useMemberGuard("我的互助资源仅面向正式会员开放");
  const router = useRouter();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const load = async () => {
    setLoading(true);
    try {
      const [profile, data] = await Promise.all([getMyProfile(), getMutualAidPosts("resource")]);
      const userId = Number(profile?.id || 0);
      const pending = Array.isArray(data?.myPendingPosts) ? data.myPendingPosts : [];
      const publishedMine = (Array.isArray(data?.publicPosts) ? data.publicPosts : []).filter((x: any) => Number(x?.publisher_id) === userId);
      const rows = [...pending, ...publishedMine];
      const highlightId = String(router.params?.highlightId || "").trim();
      if (highlightId) {
        const hitIndex = rows.findIndex((item) => String(item?.id || "") === highlightId);
        if (hitIndex >= 0) {
          const hit = rows[hitIndex];
          setItems([hit, ...rows.filter((_, index) => index !== hitIndex)]);
          setNotice(`已为你定位刚提交的资源：${hit?.title || highlightId}`);
        } else {
          setItems(rows);
          setNotice("暂未定位到刚提交的资源，请刷新后再查看。");
        }
      } else {
        setItems(rows);
        setNotice("");
      }
      setError("");
    } catch (e: any) {
      setError(e?.message || "加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void load();
  });

  const showReason = (item: any) => {
    void showActionDrawer({
      type: "info",
      title: "驳回原因",
      content: String(item?.review_reason || item?.reviewReason || "暂无驳回说明"),
      confirmText: "知道了",
      showCancel: false
    });
  };

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

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

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

        {!loading && !error && notice ? (
          <View className="my-mutual-aid-state">
            <Text>{notice}</Text>
          </View>
        ) : null}

        {!loading && !error && items.length === 0 ? (
          <View className="my-mutual-aid-state">
            <Text>暂无发布的资源</Text>
          </View>
        ) : null}

        <View className="my-mutual-aid-list">
          {items.map((item) => {
            const rejected = isRejected(item.status);
            return (
              <View key={item.id || item.title} className="my-mutual-aid-card">
                <Text className="my-mutual-aid-card__title">{item.title || "-"}</Text>
                <Text className="my-mutual-aid-card__author">
                  {(item.author || item.publisherName || item.publisher_name || "-") as string}
                  {item.role ? ` · ${item.role}` : ""}
                </Text>
                <View className="my-mutual-aid-card__row">
                  <Text className="my-mutual-aid-card__tags">{Array.isArray(item.tags) ? item.tags.join(" / ") : "-"}</Text>
                  <Text className="my-mutual-aid-card__status">{statusText(item.status, item.statusText || item.status_text)}</Text>
                </View>
                <View className="my-mutual-aid-card__row" style={{ marginTop: "8rpx", justifyContent: "flex-end", gap: "16rpx" }}>
                  {rejected ? (
                    <>
                      <Text className="my-mutual-aid-card__status" onClick={() => showReason(item)}>
                        驳回原因
                      </Text>
                      <Text className="my-mutual-aid-card__status" onClick={() => gotoEditResubmit(item)}>
                        修改后重新提交
                      </Text>
                    </>
                  ) : null}
                  <Text className="my-mutual-aid-card__status" onClick={() => void Taro.navigateTo({ url: `/pages/mutual-aid-detail/index?id=${item.id}` })}>
                    查看详情
                  </Text>
                </View>
              </View>
            );
          })}
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}
