import { Button, Image, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useEffect, useState } from "react";
import { getActivityColumns, getColumnActivities, registerActivity } from "../../api/events";
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;
  cover_image_url?: string;
  startsAt?: string;
  starts_at?: string;
  registrationCount?: number;
  display_registration_count?: number;
  capacity?: number;
};

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?.display_registration_count ?? item?.registrationCount ?? item?.registered_count ?? 0) || 0,
    capacity: Number(item?.capacity ?? 0) || 0,
  };
}

function statusText(status?: string) {
  const map: Record<string, string> = {
    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";
  return "is-pending";
}

export default function ColumnDetailPage() {
  const columnId = Number(Taro.getCurrentInstance().router?.params?.id || 0);
  const [column, setColumn] = useState<ColumnItem | null>(null);
  const [activities, setActivities] = useState<ActivityItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [submittingId, setSubmittingId] = useState<number | null>(null);
  const { showActionDrawer, actionDrawer } = useActionDrawer();

  useEffect(() => {
    if (!columnId) {
      setError("专栏ID无效");
      setLoading(false);
      return;
    }

    (async () => {
      setLoading(true);
      try {
        // 获取专栏详情
        const colData = await getActivityColumns();
        const cols = Array.isArray(colData) ? colData : [];
        const col = cols.find((c: any) => Number(c.id) === columnId);
        if (col) setColumn(col);

        // 获取专栏活动
        const actData = await getColumnActivities(columnId);
        setActivities((Array.isArray(actData) ? actData : []).map(normalizeItem));
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  }, [columnId]);

  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 {
      await registerActivity(id);
      await showActionDrawer({
        type: "success",
        title: "报名成功",
        content: "请准时参加",
        confirmText: "查看活动详情",
        showCancel: false
      });
      await openDetail(id);
    } catch (err: any) {
      Taro.showToast({ title: err?.message || "报名失败", icon: "none" });
    } finally {
      setSubmittingId(null);
    }
  };

  const goBack = () => {
    Taro.navigateBack().catch(() => Taro.switchTab({ url: "/pages/events/index" }));
  };
  const columnCoverUrl = resolveMediaUrl(firstText(column?.cover_image_url, (column as any)?.coverImageUrl, (column as any)?.image_url, (column as any)?.image));

  if (loading) {
    return (
      <View className="page-shell column-detail">
        <View className="column-detail__loading">
          <Text>加载中...</Text>
        </View>
      </View>
    );
  }

  if (error || !column) {
    return (
      <View className="page-shell column-detail">
        <View className="column-detail__error">
          <Text>{error || "专栏未找到"}</Text>
          <Button className="column-detail__back-btn" onClick={goBack}>返回</Button>
        </View>
      </View>
    );
  }

  return (
    <View className="page-shell column-detail">
      <View className="column-detail__header">
        <Text className="column-detail__title">{column.name}</Text>
        <Text className="column-detail__count">{column.activities_count ?? activities.length} 个活动</Text>
      </View>

      {column.description && (
        <View className="column-detail__desc">
          <Text>{column.description}</Text>
        </View>
      )}

      {columnCoverUrl && (
        <Image className="column-detail__cover" src={columnCoverUrl} mode="aspectFill" />
      )}

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