import { Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getMutualAidPosts, type MutualAidItem } from "../../api/mutual-aid";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import "./index.scss";

const MAIN_TABS = [
  { key: "resource", label: "资源供给" },
  { key: "need", label: "合作需求" }
] as const;

function normalizeStatusText(item: MutualAidItem) {
  const statusText = item.statusText || item.status_text;
  if (statusText) return statusText;
  const status = String(item.status || "");
  switch (status) {
    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 status || "审核中";
  }
}

function normalizeTags(item: MutualAidItem) {
  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);
}

function normalizeAuthor(item: MutualAidItem) {
  return item.publisherName || item.publisher_name || item.author || item.publisherTitle || item.publisher_title || "-";
}

export default function MutualAidPage() {
  useAuthGuard();
  const [activeTab, setActiveTab] = useState<"resource" | "need">("resource");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [publicPosts, setPublicPosts] = useState<MutualAidItem[]>([]);
  const [myPendingPosts, setMyPendingPosts] = useState<MutualAidItem[]>([]);
  const [activeSubTab, setActiveSubTab] = useState("全部");

  const loadData = async (type: "resource" | "need") => {
    setLoading(true);
    try {
      const data = await getMutualAidPosts(type);
      setPublicPosts(data.publicPosts || []);
      setMyPendingPosts(data.myPendingPosts || []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    void loadData(activeTab);
  });

  const openPublish = () => {
    const url = activeTab === "resource" ? "/pages/mutual-aid-create/index" : "/pages/demand-create/index";
    void Taro.navigateTo({ url });
  };

  const subTabs = useMemo(() => {
    const values = new Set<string>(["全部"]);
    publicPosts.forEach((item) => normalizeTags(item).forEach((tag) => values.add(tag)));
    return Array.from(values).slice(0, 8);
  }, [publicPosts]);

  const filteredPublic = useMemo(() => {
    if (activeSubTab === "全部") return publicPosts;
    return publicPosts.filter((item) => normalizeTags(item).includes(activeSubTab));
  }, [activeSubTab, publicPosts]);

  const openDetail = (id?: number) => {
    if (!id) return;
    void Taro.navigateTo({ url: `/pages/mutual-aid-detail/index?id=${id}` });
  };

  return (
    <View className="page-shell mutual-aid-page">
      <View className="page-body mutual-aid-page__body">
        <View className="mutual-aid-main-tabs">
          {MAIN_TABS.map((tab) => (
            <View
              key={tab.key}
              className={`mutual-aid-main-tab ${activeTab === tab.key ? "is-active" : ""}`}
              onClick={() => {
                setActiveTab(tab.key);
                setActiveSubTab("全部");
                void loadData(tab.key);
              }}
            >
              <Text>{tab.label}</Text>
            </View>
          ))}
        </View>

        <View className="mutual-aid-sub-tabs">
          {subTabs.map((tab) => (
            <View key={tab} className={`mutual-aid-sub-tab ${activeSubTab === tab ? "is-active" : ""}`} onClick={() => setActiveSubTab(tab)}>
              <Text>{tab}</Text>
            </View>
          ))}
        </View>

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

        {myPendingPosts.length > 0 ? (
          <View className="mutual-aid-section">
            <Text className="mutual-aid-section__title">我的待处理互助</Text>
            <View className="mutual-aid-list">
              {myPendingPosts.map((item) => (
                <View key={`pending-${item.id}`} className="card-surface mutual-aid-card">
                  <Text className="mutual-aid-card__title">{item.title || "未命名互助"}</Text>
                  <View className="mutual-aid-card__tags">
                    {normalizeTags(item).map((tag) => (
                      <Text key={`${item.id}-${tag}`} className="mutual-aid-card__tag">
                        {tag}
                      </Text>
                    ))}
                  </View>
                  <View className="mutual-aid-card__footer">
                    <View className="mutual-aid-card__author-wrap">
                      <View className="mutual-aid-card__avatar">人</View>
                      <Text className="mutual-aid-card__author">{normalizeAuthor(item)}</Text>
                    </View>
                    <Text className="mutual-aid-card__status">{normalizeStatusText(item)}</Text>
                  </View>
                  <View className="mutual-aid-card__actions">
                    <View className="mutual-aid-card__detail-btn" onClick={() => openDetail(item.id)}>
                      <Text>查看详情</Text>
                    </View>
                  </View>
                </View>
              ))}
            </View>
          </View>
        ) : null}

        <View className="mutual-aid-section">
          <Text className="mutual-aid-section__title">{activeTab === "resource" ? "资源供给" : "合作需求"}</Text>

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

          {!loading && filteredPublic.length === 0 ? (
            <View className="mutual-aid-state">
              <Text>{activeTab === "resource" ? "暂无资源供给" : "暂无合作需求"}</Text>
            </View>
          ) : null}

          <View className="mutual-aid-list">
            {filteredPublic.map((item) => (
              <View key={item.id} className="card-surface mutual-aid-card">
                <Text className="mutual-aid-card__title">{item.title || "未命名互助"}</Text>
                <View className="mutual-aid-card__tags">
                  {normalizeTags(item).map((tag) => (
                    <Text key={`${item.id}-${tag}`} className="mutual-aid-card__tag">
                      {tag}
                    </Text>
                  ))}
                </View>
                <View className="mutual-aid-card__footer">
                  <View className="mutual-aid-card__author-wrap">
                    <View className="mutual-aid-card__avatar">人</View>
                    <Text className="mutual-aid-card__author">{normalizeAuthor(item)}</Text>
                  </View>
                  <View className="mutual-aid-card__detail-btn" onClick={() => openDetail(item.id)}>
                    <Text>查看详情</Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>

        <View className="mutual-aid-bottom">
          <View className="mutual-aid-bottom__btn" onClick={openPublish}>
            <Text>{activeTab === "resource" ? "资源发布" : "需求发布"}</Text>
          </View>
        </View>
      </View>
    </View>
  );
}
