import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { checkinSelfScan, getActivityDetail, registerActivity } from "../../api/events";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { ensureMemberAccess } from "../../utils/permission";
import { firstText, resolveMediaUrl } from "../../utils/media";
import { useActionDrawer } from "../../components/action-drawer";
import "./index.scss";

function statusText(status?: string) {
  const map: Record<string, string> = {
    draft: "草稿",
    pending_branch_review: "待分会审核",
    pending_city_review: "待市级审核",
    branch_rejected: "分会驳回",
    city_rejected: "市级驳回",
    recruiting: "报名中",
    pending_start: "未开始",
    ongoing: "进行中",
    full: "已报满",
    ended: "已结束"
  };
  return map[String(status || "")] || "待确认";
}

function formatDateTime(value?: string) {
  if (!value) return "-";
  return String(value).slice(0, 16).replace("T", " ").replaceAll("-", ".");
}

function normalizeErrorMessage(msg: string) {
  const text = String(msg || "");
  if (text.includes("Only members")) return "仅会员可报名活动";
  if (text.includes("already")) return "您已报名该活动";
  if (text.includes("full")) return "活动名额已满";
  return text || "操作失败";
}

function boolValue(...values: any[]) {
  return values.some((value) => value === true || value === "true");
}

function actionState(detail: any) {
  if (detail?.canResubmit === true || detail?.can_resubmit === true) {
    return { mode: "resubmit", tone: "primary", text: "修改后重提" };
  }
  const status = String(detail?.status || "");
  const registrationStatus = String(detail?.registrationStatus || detail?.registration_status || "");
  const registrationMessage = firstText(detail?.registrationMessage, detail?.registration_message);
  const checkinMessage = firstText(detail?.checkinMessage, detail?.checkin_message);
  const isFull = boolValue(detail?.isFull, detail?.is_full);
  const deadlinePassed = boolValue(detail?.registrationDeadlinePassed, detail?.registration_deadline_passed);
  const canRegister = boolValue(detail?.canRegister, detail?.can_register);
  const canCheckin = boolValue(detail?.canCheckin, detail?.can_checkin);

  if (canRegister) return { mode: "register", tone: "primary", text: "立即报名" };
  if (canCheckin) return { mode: "checkin", tone: "primary", text: "扫码签到" };

  if (registrationStatus === "registered") {
    return {
      mode: "disabled",
      tone: detail?.checkinStatus === "checked" || detail?.checkin_status === "checked" ? "muted" : "warn",
      text: checkinMessage || "已报名，等待签到",
    };
  }

  if (status === "recruiting" && !isFull && !deadlinePassed) {
    return { mode: "register", tone: "primary", text: registrationMessage || "立即报名" };
  }
  if (status === "pending_start") return { mode: "disabled", tone: "warn", text: registrationMessage || "活动未开始" };
  if (status === "full") return { mode: "disabled", tone: "muted", text: registrationMessage || "名额已满" };
  return { mode: "disabled", tone: "muted", text: registrationMessage || "当前不可操作" };
}

export default function ActivityDetailPage() {
  useMemberGuard("活动仅面向正式会员开放");

  const { params } = useRouter();
  const activityId = params?.id;
  const [loading, setLoading] = useState(false);
  const [detail, setDetail] = useState<any>(null);
  const [error, setError] = useState("");
  const [doing, setDoing] = useState("");
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const load = async () => {
    if (!activityId) return;
    setLoading(true);
    try {
      const data = await getActivityDetail(activityId);
      setDetail(data);
      setError("");
    } catch (e: any) {
      setError(e?.message || "活动详情加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const onRegister = async () => {
    if (!activityId) return;
    const ok = await ensureMemberAccess("仅会员可报名活动");
    if (!ok) return;
    const confirm = await showActionDrawer({
      type: "confirm",
      title: "请再次确认您报名参加",
      content: detail?.title || "该活动",
      confirmText: "确认",
      cancelText: "取消"
    });
    if (!confirm.confirm) return;
    setDoing("register");
    try {
      const result = await registerActivity(activityId);
      const alreadyRegistered = boolValue(result?.alreadyRegistered, result?.already_registered);
      await load();
      await showActionDrawer({
        type: "success",
        title: alreadyRegistered ? "您已报名" : "报名成功",
        content: alreadyRegistered ? "无需重复提交，可在活动详情查看签到状态" : "请准时参加",
        confirmText: "查看活动详情",
        showCancel: false
      });
    } catch (err: any) {
      Taro.showToast({ title: normalizeErrorMessage(err?.message), icon: "none" });
    } finally {
      setDoing("");
    }
  };

  const onCheckin = async () => {
    if (!activityId) return;
    setDoing("checkin");
    try {
      const scan = await Taro.scanCode({ onlyFromCamera: true });
      const checkinCode = parseCheckinCode(scan?.result || "");
      if (!checkinCode) {
        Taro.showToast({ title: "未识别到活动签到码", icon: "none" });
        return;
      }
      const res = await checkinSelfScan(activityId, checkinCode);
      const status = String(res?.status || "");
      const msg =
        status === "checked_in"
          ? "签到成功"
          : status === "already_checked_in"
            ? "已签到"
            : status === "unregistered_recorded"
              ? "未报名，已记录待核实"
              : "操作完成";
      Taro.showToast({ title: msg, icon: "none" });
      await load();
    } finally {
      setDoing("");
    }
  };

  const currentAction = useMemo(() => actionState(detail), [detail]);
  const coverImage = resolveMediaUrl(firstText(detail?.coverImageUrl, detail?.cover_image_url, detail?.imageUrl, detail?.image_url, detail?.image));
  const reviewReason = firstText(detail?.reviewReason, detail?.review_reason);

  return (
    <View className="page-shell activity-detail-page">
      <View className="page-body activity-detail-page__body">
        {error ? (
          <View className="activity-detail-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        {loading && !detail ? (
          <View className="card-surface activity-detail-empty">
            <Text>加载中...</Text>
          </View>
        ) : null}

        {detail ? (
          <>
            <View className="card-surface activity-detail-main">
              <View className="activity-detail-main__head">
                <Text className="activity-detail-main__title">{detail.title || "未命名活动"}</Text>
                <Text className="activity-detail-main__status">{statusText(detail.status)}</Text>
              </View>

              {coverImage ? (
                <Image className="activity-detail-main__cover" src={coverImage} mode="aspectFill" />
              ) : (
                <View className="activity-detail-main__cover is-empty">
                  <Text>暂无活动图片</Text>
                </View>
              )}

              <View className="activity-detail-main__rows">
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">活动时间</Text>
                  <Text className="activity-detail-main__value">{`${formatDateTime(detail.starts_at || detail.startsAt)} ~ ${formatDateTime(detail.ends_at || detail.endsAt)}`}</Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">活动地点</Text>
                  <Text className="activity-detail-main__value">{detail.location || "-"}</Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">所属分会</Text>
                  <Text className="activity-detail-main__value">{detail.branch_name || detail.branchName || "待补充"}</Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">报名人数</Text>
                  <Text className="activity-detail-main__value">
                    {(detail.registered_count ?? detail.registration_count ?? detail.display_registration_count ?? 0)}/{detail.capacity || "-"} 人
                  </Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">报名截止</Text>
                  <Text className="activity-detail-main__value">{formatDateTime(detail.register_deadline || detail.registerDeadline)}</Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">报名状态</Text>
                  <Text className="activity-detail-main__value">{detail.registrationMessage || detail.registration_message || "请确认后报名"}</Text>
                </View>
                <View className="activity-detail-main__row">
                  <Text className="activity-detail-main__label">签到状态</Text>
                  <Text className="activity-detail-main__value">{detail.checkinMessage || detail.checkin_message || "报名后可查看"}</Text>
                </View>
              </View>
            </View>

            {reviewReason ? (
              <View className="activity-detail-reason">
                <Text>驳回原因：{reviewReason}</Text>
              </View>
            ) : null}

            <View className="card-surface activity-detail-content">
              <Text className="activity-detail-content__title">活动详情</Text>
              <Text className="activity-detail-content__text">{detail.description || "暂无详情"}</Text>
            </View>
          </>
        ) : null}

        <View className="activity-detail-action-bar">
          {currentAction.mode === "register" ? (
            <Button className="activity-detail-action is-primary" loading={doing === "register"} onClick={() => void onRegister()}>
              {currentAction.text}
            </Button>
          ) : null}

          {currentAction.mode === "checkin" ? (
            <Button className="activity-detail-action is-primary" loading={doing === "checkin"} onClick={() => void onCheckin()}>
              {currentAction.text}
            </Button>
          ) : null}

          {currentAction.mode === "resubmit" ? (
            <Button className="activity-detail-action is-primary" onClick={() => void Taro.navigateTo({ url: `/pages/event-create/index?id=${activityId}` })}>
              {currentAction.text}
            </Button>
          ) : null}

          {currentAction.mode === "disabled" ? (
            <Button className={`activity-detail-action ${currentAction.tone === "warn" ? "is-warn" : "is-muted"}`} disabled>
              {currentAction.text}
            </Button>
          ) : null}
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}

function parseCheckinCode(value: string) {
  const text = String(value || "").trim();
  if (!text) return "";
  try {
    const url = new URL(text);
    return url.searchParams.get("checkinCode") || url.searchParams.get("code") || "";
  } catch {
    const match = text.match(/(?:checkinCode|code)=([^&]+)/i);
    return match ? decodeURIComponent(match[1]) : text;
  }
}
