import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getActivities, getActivityColumns, getColumnActivities, 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";

type ColumnItem = {
  id: number;
  name: string;
  cover_image_url?: string;
  description?: string;
  activities_count?: number;
};

type ActivityItem = {
  id: number;
  title?: string;
  status?: string;
  location?: string;
  coverImageUrl?: string;
  startsAt?: string;
  registrationCount?: number;
  capacity?: number;
  columnId?: number | null;
};

function normalizeList(data: any) {
  if (Array.isArray(data)) return { myPendingActivities: [], publicActivities: data };
  return {
    myPendingActivities: Array.isArray(data?.myPendingActivities) ? data.myPendingActivities : [],
    publicActivities: Array.isArray(data?.publicActivities) ? data.publicActivities : []
  };
}

function normalizeItem(item: any): ActivityItem {
  return {
    id: Number(item?.id),
    title: item?.title || "",
    status: item?.status || "",
    location: item?.location || "",
    coverImageUrl: resolveMediaUrl(firstText(item?.coverImageUrl, item?.cover_image_url, item?.imageUrl, item?.image_url, item?.image)),
    startsAt: item?.startsAt || item?.starts_at || "",
    registrationCount:
      Number(
        item?.registrationCount ??
          item?.displayRegistrationCount ??
          item?.display_registration_count ??
          item?.registeredCount ??
          item?.registered_count ??
          0
      ) || 0,
    capacity: Number(item?.capacity ?? 0) || 0,
    columnId: item?.columnId ?? item?.column_id ?? null,
  };
}

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 statusClass(status?: string) {
  if (status === "recruiting" || status === "ongoing") return "is-primary";
  if (status === "pending_start") return "is-warn";
  if (status === "full" || status === "ended") return "is-muted";
  if (status?.includes("rejected")) return "is-danger";
  return "is-pending";
}

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");
}

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

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [pending, setPending] = useState<ActivityItem[]>([]);
  const [publicList, setPublicList] = useState<ActivityItem[]>([]);
  const [columns, setColumns] = useState<ColumnItem[]>([]);
  const [activeColumnId, setActiveColumnId] = useState<number | null>(null);
  const [columnActivities, setColumnActivities] = useState<ActivityItem[]>([]);
  const [submittingId, setSubmittingId] = useState<number | null>(null);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  const load = async () => {
    setLoading(true);
    try {
      const data = await getActivities();
      const parsed = normalizeList(data);
      setPending(parsed.myPendingActivities.map(normalizeItem));
      const allPublic = parsed.publicActivities.map(normalizeItem);
      setPublicList(allPublic);
      setError("");

      // 加载专栏列表
      const colData = await getActivityColumns();
      setColumns(Array.isArray(colData) ? colData : []);
    } catch (e: any) {
      setError(e?.message || "活动加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  // 未关联专栏的普通活动
  const normalActivities = useMemo(
    () => publicList.filter((item) => !item.columnId),
    [publicList]
  );

  const handleColumnTap = async (columnId: number) => {
    if (activeColumnId === columnId) {
      setActiveColumnId(null);
      setColumnActivities([]);
      return;
    }
    setActiveColumnId(columnId);
    try {
      const data = await getColumnActivities(columnId);
      const items = (Array.isArray(data) ? data : []).map(normalizeItem);
      setColumnActivities(items);
    } catch {
      setColumnActivities([]);
    }
  };

  const openDetail = async (id: number) => {
    await Taro.navigateTo({ url: `/pages/activity-detail/index?id=${id}` });
  };

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

  const gotoCreate = async () => {
    await Taro.navigateTo({ url: "/pages/event-create/index" });
  };

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

        {pending.length > 0 ? (
          <View className="card-surface events-pending">
            <Text className="events-section-title">我的待处理活动</Text>
            <View className="events-pending__list">
              {pending.map((item) => (
                <View key={`pending-${item.id}`} className="events-pending__item" onClick={() => void openDetail(item.id)}>
                  <Text className="events-pending__name">{item.title || "未命名活动"}</Text>
                  <Text className={`events-pending__status ${statusClass(item.status)}`}>{statusText(item.status)}</Text>
                </View>
              ))}
            </View>
          </View>
        ) : null}

        {/* 品牌活动专栏 - 动态获取 */}
        {columns.length > 0 && (
          <View className="events-brand">
            <Text className="events-section-title">"新联中国"品牌活动</Text>
            <View className="events-brand__grid">
              {columns.map((col, index) => (
                <View
                  key={col.id}
                  className={`events-brand__item events-brand__item--${(index % 4) + 1} ${activeColumnId === col.id ? "events-brand__item--active" : ""}`}
                  onClick={() => void handleColumnTap(col.id)}
                >
                  <Text className="events-brand__text">{col.name}</Text>
                </View>
              ))}
            </View>

            {/* 专栏展开的活动列表 */}
            {activeColumnId !== null && (
              <View className="events-column-activities">
                {columnActivities.length > 0 ? (
                  columnActivities.map((item) => (
                    <View key={item.id} className="card-surface events-card" onClick={() => void openDetail(item.id)}>
                      <View className="events-card__row">
                        <View className="events-card__media">
                          <View className="events-card__cover">
                            {item.coverImageUrl ? (
                              <Image className="events-card__cover-image" src={item.coverImageUrl} mode="aspectFill" />
                            ) : (
                              <View className="events-card__cover-empty">
                                <Text>暂无图片</Text>
                              </View>
                            )}
                          </View>
                          <View className="events-card__count">
                            <Text>{item.registrationCount}/{item.capacity || "-"}人</Text>
                          </View>
                        </View>
                        <View className="events-card__content">
                          <Text className="events-card__title">{item.title || "未命名活动"}</Text>
                          <View className="events-card__meta">
                            <Text className="events-card__meta-line">时间：{formatDateTime(item.startsAt)}</Text>
                            <Text className="events-card__meta-line">地点：{item.location || "待补充"}</Text>
                          </View>
                          <View className="events-card__footer">
                            <Text className={`events-card__badge ${statusClass(item.status)}`}>{statusText(item.status)}</Text>
                            <Button
                              className="events-card__button"
                              size="mini"
                              loading={submittingId === item.id}
                              disabled={item.status !== "recruiting"}
                              onClick={(e) => void onRegister(e, item)}
                            >
                              报名
                            </Button>
                          </View>
                        </View>
                      </View>
                    </View>
                  ))
                ) : (
                  <View className="card-surface events-empty">
                    <Text>该专栏暂无活动</Text>
                  </View>
                )}
              </View>
            )}
          </View>
        )}

        <View className="events-public">
          <View className="section-title-row">
            <Text className="section-title">推荐活动</Text>
          </View>

          <View className="events-public__list">
            {(normalActivities.length > 0 ? normalActivities : publicList).map((item) => (
              <View key={item.id} className="card-surface events-card" onClick={() => void openDetail(item.id)}>
                <View className="events-card__row">
                  <View className="events-card__media">
                    <View className="events-card__cover">
                      {item.coverImageUrl ? (
                        <Image className="events-card__cover-image" src={item.coverImageUrl} mode="aspectFill" />
                      ) : (
                        <View className="events-card__cover-empty">
                          <Text>暂无图片</Text>
                        </View>
                      )}
                    </View>
                    <View className="events-card__count">
                      <Text>{item.registrationCount}/{item.capacity || "-"}人</Text>
                    </View>
                  </View>

                  <View className="events-card__content">
                    <Text className="events-card__title">{item.title || "未命名活动"}</Text>
                    <View className="events-card__meta">
                      <Text className="events-card__meta-line">时间：{formatDateTime(item.startsAt)}</Text>
                      <Text className="events-card__meta-line">地点：{item.location || "待补充"}</Text>
                    </View>
                    <View className="events-card__footer">
                      <Text className={`events-card__badge ${statusClass(item.status)}`}>{statusText(item.status)}</Text>
                      <Button
                        className="events-card__button"
                        size="mini"
                        loading={submittingId === item.id}
                        disabled={item.status !== "recruiting"}
                        onClick={(e) => void onRegister(e, item)}
                      >
                        报名
                      </Button>
                    </View>
                  </View>
                </View>
              </View>
            ))}

            {!loading && normalActivities.length === 0 && columns.length === 0 ? (
              <View className="card-surface events-empty">
                <Text>暂无公开活动</Text>
              </View>
            ) : null}
          </View>
        </View>

        <View className="events-create-bar">
          <Button className="events-create-button" onClick={() => void gotoCreate()}>
            活动发布
          </Button>
        </View>
      </View>
      {actionDrawer}
    </View>
  );
}
