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

function firstText(...values: any[]) {
  const value = values.find((item) => item !== undefined && item !== null && String(item).trim() !== "");
  return value === undefined || value === null ? "" : String(value);
}

function activityStatusText(status: any) {
  const map: Record<string, string> = {
    recruiting: "报名中",
    pending_start: "待开始",
    ongoing: "进行中",
    full: "已报满",
    ended: "已结束",
    archived: "已归档",
    cancelled: "已取消",
    canceled: "已取消"
  };
  const key = String(status || "").toLowerCase();
  return map[key] || String(status || "待确认");
}

function registrationText(item: any) {
  const text = firstText(item.registrationStatusText, item.registration_status_text);
  if (text) return text;
  const status = String(firstText(item.registrationStatus, item.registration_status)).toLowerCase();
  if (status === "registered") return "已报名";
  if (status === "cancelled" || status === "canceled") return "已取消";
  return status || "报名记录";
}

function checkedIn(item: any) {
  return item.checkedIn === true || item.checked_in === true || item.checkedIn === "true" || item.checked_in === "true";
}

function checkinText(item: any) {
  if (checkedIn(item)) {
    return firstText(item.checkedInAt, item.checked_in_at) ? `已签到 ${firstText(item.checkedInAt, item.checked_in_at)}` : "已签到";
  }
  const status = String(item.status || "").toLowerCase();
  if (status === "ended" || status === "archived") return "未签到";
  return "待签到";
}

function displayDate(item: any) {
  return firstText(item.date)
    || (item.starts_at ? String(item.starts_at).slice(0, 10).replaceAll("-", ".") : "")
    || firstText(item.registeredAt, item.registered_at)
    || "-";
}

export default function MyRegisteredActivitiesPage() {
  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 getMyRegisteredActivities();
        const rows = Array.isArray(data) ? data : [];
        const highlightId = String(router.params?.highlightId || "").trim();
        if (highlightId) {
          const hitIndex = rows.findIndex((item) => String(item?.activity_id || item?.id || "") === highlightId);
          if (hitIndex >= 0) {
            const hit = rows[hitIndex];
            setItems([hit, ...rows.filter((_, index) => index !== hitIndex)]);
            setNotice(`已为你定位刚报名的活动：${hit?.title || hit?.activity_title || highlightId}`);
          } else {
            setItems(rows);
            setNotice("暂未定位到刚报名的活动，请刷新后再查看。");
          }
        } else {
          setItems(rows);
          setNotice("");
        }
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

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

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

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

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

        <View className="my-registered-activities-list">
          {items.map((item) => (
            <View
              key={item.id || item.activity_id || item.title}
              className="my-registered-activities-card"
              onClick={() => void Taro.navigateTo({ url: `/pages/activity-detail/index?id=${item.activity_id || item.id}` })}
            >
              <Text className="my-registered-activities-card__title">{item.title || item.activity_title || "-"}</Text>
              <View className="my-registered-activities-card__row">
                <Text className="my-registered-activities-card__meta">{displayDate(item)} · {item.location || "地点待定"}</Text>
                <Text className="my-registered-activities-card__status">{activityStatusText(item.status)}</Text>
              </View>
              <View className="my-registered-activities-card__badges">
                <Text className="my-registered-activities-card__badge">{registrationText(item)}</Text>
                <Text className={`my-registered-activities-card__badge ${checkedIn(item) ? "is-success" : "is-warn"}`}>{checkinText(item)}</Text>
              </View>
              <View className="my-registered-activities-card__detail">
                <Text>报名时间：{firstText(item.registeredAt, item.registered_at) || "-"}</Text>
                <Text>报名凭证：{firstText(item.voucherNo, item.voucher_no) || "-"}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
