import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getBranchDetail } from "../../api/branches";
import "./index.scss";

function statusText(value?: string) {
  switch (value) {
    case "recruiting":
      return "报名中";
    case "pending_start":
      return "未开始";
    case "ongoing":
      return "进行中";
    case "ended":
      return "已结束";
    case "full":
      return "已满员";
    default:
      return value || "-";
  }
}

const eventTabs = ["全部", "正在进行", "未开始", "已结束"];
const serviceTabs = ["全部", "正在进行", "未开始", "已结束"];

export default function BranchDetailPage() {
  const { params } = useRouter();
  const id = params?.id;

  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [eventTab, setEventTab] = useState("全部");
  const [serviceTab, setServiceTab] = useState("全部");

  useDidShow(() => {
    if (!id) return;
    void (async () => {
      setLoading(true);
      try {
        const data = await getBranchDetail(id);
        setDetail(data || null);
        setError("");
      } catch (e: any) {
        setError(e?.message || "加载失败");
      } finally {
        setLoading(false);
      }
    })();
  });

  const branch = detail?.branch || {};
  const stats = detail?.stats || {};
  const events = Array.isArray(detail?.events) ? detail.events : [];
  const services = Array.isArray(detail?.services) ? detail.services : [];

  const filteredEvents = useMemo(() => {
    if (eventTab === "全部") return events;
    if (eventTab === "正在进行") return events.filter((item: any) => item.status === "recruiting" || item.status === "ongoing");
    if (eventTab === "未开始") return events.filter((item: any) => item.status === "pending_start");
    if (eventTab === "已结束") return events.filter((item: any) => item.status === "ended");
    return events;
  }, [events, eventTab]);

  const filteredServices = useMemo(() => {
    if (serviceTab === "全部") return services;
    if (serviceTab === "正在进行") return services.filter((item: any) => item.status === "published" || item.status === "ongoing");
    if (serviceTab === "未开始") return services.filter((item: any) => item.status === "pending_start");
    if (serviceTab === "已结束") return services.filter((item: any) => item.status === "ended");
    return services;
  }, [services, serviceTab]);

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

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

        <View className="branch-detail-hero">
          <View className="branch-detail-hero__bubble branch-detail-hero__bubble--top" />
          <View className="branch-detail-hero__bubble branch-detail-hero__bubble--bottom" />
          <Text className="branch-detail-hero__subtitle">{branch.home_subtitle || "大连市新联会分会"}</Text>
          <Text className="branch-detail-hero__title">{branch.short_name || branch.name || "-"}</Text>
          <View className="branch-detail-hero__score">
            <Text>积分 {stats.pointTotal || 0}</Text>
          </View>
        </View>

        <View className="branch-detail-stats">
          <View className="branch-detail-stats__item">
            <Text className="branch-detail-stats__value">{stats.newsCount || 0}</Text>
            <Text className="branch-detail-stats__label">发布新闻资讯</Text>
          </View>
          <View className="branch-detail-stats__item">
            <Text className="branch-detail-stats__value">{stats.learningViewCount || 0}</Text>
            <Text className="branch-detail-stats__label">参与学习次数</Text>
          </View>
          <View className="branch-detail-stats__item">
            <Text className="branch-detail-stats__value">{stats.suggestionAdoptedCount || 0}</Text>
            <Text className="branch-detail-stats__label">建言采纳</Text>
          </View>
          {services.length > 0 ? (
            <View className="branch-detail-stats__item">
              <Text className="branch-detail-stats__value">{services.length || 0}</Text>
              <Text className="branch-detail-stats__label">社会服务项目</Text>
            </View>
          ) : null}
          <View className="branch-detail-stats__item">
            <Text className="branch-detail-stats__value">{stats.eventCount || 0}</Text>
            <Text className="branch-detail-stats__label">活动数量</Text>
          </View>
        </View>

        <View className="branch-detail-section">
          <View className="branch-detail-section__head">
            <Text className="branch-detail-section__title">活动报名</Text>
          </View>
          <View className="branch-detail-tabs">
            {eventTabs.map((tab) => (
              <View key={tab} className={`branch-detail-tabs__item ${eventTab === tab ? "is-active" : ""}`} onClick={() => setEventTab(tab)}>
                <Text>{tab}</Text>
              </View>
            ))}
          </View>
          <View className="branch-detail-list">
            {filteredEvents.length === 0 ? (
              <Text className="branch-detail-empty">暂无活动</Text>
            ) : (
              filteredEvents.slice(0, 2).map((item: any) => (
                <View key={item.id} className="branch-detail-card" onClick={() => void Taro.navigateTo({ url: `/pages/activity-detail/index?id=${item.id}` })}>
                  <View className="branch-detail-card__media">
                    {item.coverImageUrl ? <Image className="branch-detail-card__image" src={item.coverImageUrl} mode="aspectFill" /> : null}
                    <View className="branch-detail-card__count">
                      <Text>已报名</Text>
                      <Text className="branch-detail-card__count-value">
                        {(item.display_registration_count || item.registered_count || 0)}/{item.capacity || "-"}人
                      </Text>
                    </View>
                  </View>
                  <View className="branch-detail-card__content">
                    <Text className="branch-detail-card__title">{item.title || "-"}</Text>
                    <Text className="branch-detail-card__meta">{item.starts_at || item.startsAt || "-"}</Text>
                    <Text className="branch-detail-card__meta">{item.location || "-"}</Text>
                    <View className="branch-detail-card__action-row">
                      <Button className={`branch-detail-card__action ${item.status === "recruiting" ? "is-primary" : ""}`}>{statusText(item.status)}</Button>
                    </View>
                  </View>
                </View>
              ))
            )}
          </View>
        </View>

        {services.length > 0 ? (
          <View className="branch-detail-section">
            <View className="branch-detail-section__head">
              <Text className="branch-detail-section__title">社会服务项目</Text>
            </View>
            <View className="branch-detail-tabs">
              {serviceTabs.map((tab) => (
                <View key={tab} className={`branch-detail-tabs__item ${serviceTab === tab ? "is-active" : ""}`} onClick={() => setServiceTab(tab)}>
                  <Text>{tab}</Text>
                </View>
              ))}
            </View>
            <View className="branch-detail-list">
              {filteredServices.length === 0 ? (
                <Text className="branch-detail-empty">暂无社会服务项目</Text>
              ) : (
                filteredServices.slice(0, 2).map((item: any) => (
                  <View key={item.id} className="branch-detail-card" onClick={() => void Taro.navigateTo({ url: `/pages/service-detail/index?id=${item.id}` })}>
                    <View className="branch-detail-card__media">
                      {item.coverImageUrl ? <Image className="branch-detail-card__image" src={item.coverImageUrl} mode="aspectFill" /> : null}
                    </View>
                    <View className="branch-detail-card__content">
                      <Text className="branch-detail-card__title">{item.title || "-"}</Text>
                      <Text className="branch-detail-card__meta">{item.starts_at || item.startsAt || "-"}</Text>
                      <Text className="branch-detail-card__meta">{item.location || "-"}</Text>
                      <View className="branch-detail-card__action-row">
                        <Button className={`branch-detail-card__action ${item.status === "published" ? "is-primary" : ""}`}>
                          {item.status === "published" ? "详情" : statusText(item.status)}
                        </Button>
                      </View>
                    </View>
                  </View>
                ))
              )}
            </View>
          </View>
        ) : null}
      </View>
    </View>
  );
}
