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

function statusText(item: any) {
  const explicit = String(item?.statusText || item?.status_text || "").trim();
  if (explicit) return explicit;
  const map: Record<string, string> = {
    recruiting: "报名中",
    ongoing: "进行中",
    pending_start: "待开始",
    full: "已满员",
    ended: "已结束",
    draft: "审核中",
    pending_branch_review: "分会审核中",
    pending_city_review: "市级审核中",
    rejected: "已驳回",
    branch_rejected: "已驳回",
    city_rejected: "已驳回",
    archived: "已归档"
  };
  return map[String(item?.status || "")] || String(item?.status || "-");
}

function canResubmit(item: any) {
  return item?.canResubmit === true || item?.can_resubmit === true || ["rejected", "branch_rejected", "city_rejected"].includes(String(item?.status || ""));
}

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

export default function MyCreatedActivitiesPage() {
  useAuthGuard();
  useMemberGuard("我发布的活动仅面向正式会员开放");
  const router = useRouter();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const data = await getMyCreatedActivities();
        const rows = Array.isArray(data) ? data : [];
        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);
      }
    })();
  });

  return (
    <View className="my-created-activities-page">
      <View className="my-created-activities-page__body">
        <View className="my-created-activities-page__action">
          <Button className="my-created-activities-page__button" onClick={() => void Taro.navigateTo({ url: "/pages/event-create/index" })}>
            发布活动
          </Button>
        </View>

        {error ? (
          <View className="my-created-activities-state is-error">
            <Text>{error}</Text>
          </View>
        ) : null}

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

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

        {!loading && !error && items.length === 0 ? (
          <View className="my-created-activities-state">
            <Text>暂无发布活动</Text>
          </View>
        ) : null}

        <View className="my-created-activities-list">
          {items.map((item) => {
            const reason = reviewReason(item);
            return (
              <View
                key={item.id || item.title}
                className="my-created-activities-card"
                onClick={() => void Taro.navigateTo({ url: `/pages/activity-detail/index?id=${item.id}` })}
              >
                <Text className="my-created-activities-card__title">{item.title || "-"}</Text>
                <View className="my-created-activities-card__row">
                  <Text className="my-created-activities-card__meta">{item.starts_at ? String(item.starts_at).slice(0, 10).replaceAll("-", ".") : item.date || "-"}</Text>
                  <Text className="my-created-activities-card__status">{statusText(item)}</Text>
                </View>
                {item.branch_names ? <Text className="my-created-activities-card__branch">{item.branch_names}</Text> : null}
                {reason ? (
                  <View className="my-created-activities-card__reason">
                    <Text>驳回原因：{reason}</Text>
                  </View>
                ) : null}
                {canResubmit(item) ? (
                  <Button
                    className="my-created-activities-card__edit"
                    onClick={(event) => {
                      event.stopPropagation();
                      void Taro.navigateTo({ url: `/pages/event-create/index?id=${item.id}` });
                    }}
                  >
                    修改后重提
                  </Button>
                ) : null}
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
