import { Image, Swiper, SwiperItem, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useMemo, useState } from "react";
import { getHomeData } from "../../api/home";
import newsIcon from "../../assets/home-icons/news.svg";
import learningIcon from "../../assets/home-icons/learning.svg";
import suggestionsIcon from "../../assets/home-icons/suggestions.svg";
import servicesIcon from "../../assets/home-icons/services.svg";
import membersIcon from "../../assets/home-icons/members.svg";
import surveyIcon from "../../assets/home-icons/survey.svg";
import eventsIcon from "../../assets/home-icons/events.svg";
import joinIcon from "../../assets/home-icons/join.svg";
import { normalizeMediaAccounts } from "../../utils/mediaMatrix";
import { firstText, resolveMediaUrl } from "../../utils/media";
import "./index.scss";

type HomeModule = {
  code: string;
  name?: string;
  path?: string;
  iconSrc?: string;
};

type HomeBranch = {
  id: number;
  name?: string;
  shortName?: string;
  short_name?: string;
  title?: string;
  homeTitle?: string;
  home_title?: string;
};

type HomeBanner = {
  id?: number;
  title?: string;
  image_url?: string;
  link_url?: string;
};

type GuessCard = {
  targetType?: string;
  targetId?: number;
  category?: string;
  title?: string;
  coverImageUrl?: string;
  sourceName?: string;
  viewCount?: number;
  startsAt?: string;
  registrationCount?: number;
  capacity?: number;
  actionText?: string;
};

const MODULE_DEFAULTS = [
  { code: "news", name: "新闻资讯", path: "/news", iconSrc: newsIcon },
  { code: "learning", name: "学习园地", path: "/learning", iconSrc: learningIcon },
  { code: "suggestions", name: "建言献策", path: "/suggestions", iconSrc: suggestionsIcon },
  { code: "services", name: "社会服务", path: "/services", iconSrc: servicesIcon },
  { code: "members", name: "会员风采", path: "/members", iconSrc: membersIcon },
  { code: "survey", name: "调查问卷", path: "/survey", iconSrc: surveyIcon },
  { code: "events", name: "活动报名", path: "/events", iconSrc: eventsIcon },
  { code: "join", name: "加入会员", path: "/join", iconSrc: joinIcon }
];

function formatDate(value?: string) {
  if (!value) return "";
  return String(value).slice(0, 10).replaceAll("-", ".");
}

function normalizeGuessCard(item: any): GuessCard {
  return {
    targetType: item?.targetType || "content",
    targetId: item?.targetId,
    category: item?.category,
    title: item?.title,
    coverImageUrl: resolveMediaUrl(firstText(item?.coverImageUrl, item?.cover_image_url, item?.imageUrl, item?.image_url, item?.image)),
    sourceName: item?.sourceName || "",
    viewCount: item?.viewCount || 0,
    startsAt: item?.startsAt || "",
    registrationCount: item?.registrationCount || 0,
    capacity: item?.capacity || 0,
    actionText: item?.actionText || (item?.targetType === "activity" ? "报名" : "查看")
  };
}

function getGuessCategoryText(item: GuessCard) {
  if (item.targetType === "activity") return "活动报名";
  if (item.category === "learning") return "学习园地";
  if (item.category === "member_showcase") return "会员风采";
  return "新闻资讯";
}

function normalizePath(raw?: string) {
  const p = (raw || "").trim().toLowerCase();
  if (!p) return "";
  if (p === "/event" || p === "/activities" || p === "/activity") return "/events";
  if (p === "/service") return "/services";
  if (p === "/member" || p === "/members-showcase") return "/members";
  if (p === "/surveys") return "/survey";
  if (p === "/suggestion") return "/suggestions";
  if (p === "/about" || p === "/about/intro") return "/about/intro";
  if (p === "/about/structure") return "/about/structure";
  return p;
}

function normalizeBranchTitle(item: HomeBranch) {
  return firstText(item?.homeTitle, item?.home_title, item?.title, item?.shortName, item?.short_name, item?.name)
    .replace(/^大连市新的社会阶层人士联谊会/, "")
    .replace(/^大连市新联会/, "")
    .replace(/^大连新联会/, "")
    .replace(/分会$/, "")
    .replace(/专委会$/, "")
    .trim();
}

export default function HomePage() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [homeData, setHomeData] = useState<any>(null);
  const [showAllBranches, setShowAllBranches] = useState(false);

  const loadData = async () => {
    setLoading(true);
    try {
      const data = await getHomeData();
      setHomeData(data || {});
      setError("");
    } catch (e: any) {
      setError(e?.message || "首页数据加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const modules = useMemo(() => {
    const byCode = new Map<string, HomeModule>((homeData?.modules || []).map((item: HomeModule) => [item.code, item]));
    return MODULE_DEFAULTS.map((base) => {
      const actual = byCode.get(base.code);
      return {
        ...base,
        name: actual?.name || base.name,
        path: normalizePath(actual?.path || base.path)
      };
    });
  }, [homeData]);

  const branches = useMemo(() => {
    return (homeData?.branches || []).map((item: HomeBranch) => {
      return { id: item.id, name: normalizeBranchTitle(item) };
    });
  }, [homeData]);

  const visibleBranches = showAllBranches ? branches : branches.slice(0, 4);

  const mediaAccounts = useMemo(() => normalizeMediaAccounts(homeData?.mediaAccounts || []), [homeData]);

  const mediaPreview = useMemo(() => {
    const seen = new Set<string>();
    return mediaAccounts.filter((account) => {
      if (seen.has(account.platformKey)) return false;
      seen.add(account.platformKey);
      return true;
    }).slice(0, 4);
  }, [mediaAccounts]);

  const guessCards = useMemo(() => {
    const list = (homeData?.guessYouLike || []).map(normalizeGuessCard);
    if (list.length > 0) return list.slice(0, 8);

    const news = homeData?.recommendedNews || [];
    const activities = homeData?.recommendedActivities || [];
    return [
      news[0]
        ? normalizeGuessCard({
            targetType: "content",
            targetId: news[0].id,
            category: news[0].type,
            title: news[0].title,
            coverImageUrl: firstText(news[0].coverImageUrl, news[0].cover_image_url, news[0].imageUrl, news[0].image_url, news[0].image),
            sourceName: news[0].sourceName,
            viewCount: news[0].view_count,
            startsAt: news[0].published_at
          })
        : null,
      activities[0]
        ? normalizeGuessCard({
            targetType: "activity",
            targetId: activities[0].id,
            category: "events",
            title: activities[0].title,
            coverImageUrl: firstText(activities[0].coverImageUrl, activities[0].cover_image_url, activities[0].imageUrl, activities[0].image_url, activities[0].image),
            registrationCount: activities[0].display_registration_count,
            capacity: activities[0].capacity
          })
        : null,
      news[1]
        ? normalizeGuessCard({
            targetType: "content",
            targetId: news[1].id,
            category: news[1].type,
            title: news[1].title,
            coverImageUrl: firstText(news[1].coverImageUrl, news[1].cover_image_url, news[1].imageUrl, news[1].image_url, news[1].image),
            sourceName: news[1].sourceName,
            viewCount: news[1].view_count,
            startsAt: news[1].published_at
          })
        : null
    ].filter(Boolean) as GuessCard[];
  }, [homeData]);

  const gotoPath = (path: string) => {
    const p = normalizePath(path);
    if (p === "/events") return Taro.navigateTo({ url: "/pages/events/index" });
    if (p === "/services") return Taro.navigateTo({ url: "/pages/services/index" });
    if (p === "/social") return Taro.switchTab({ url: "/pages/social/index" });
    if (p === "/profile") return Taro.switchTab({ url: "/pages/profile/index" });
    if (p === "/join") return Taro.navigateTo({ url: "/pages/join/index" });
    if (p === "/suggestions") return Taro.navigateTo({ url: "/pages/suggestions/index" });
    if (p === "/survey") return Taro.navigateTo({ url: "/pages/survey/index" });
    if (p === "/news") return Taro.navigateTo({ url: "/pages/news-list/index" });
    if (p === "/learning") return Taro.navigateTo({ url: "/pages/learning-list/index" });
    if (p === "/members") return Taro.navigateTo({ url: "/pages/member-showcase/index" });
    if (p === "/search") return Taro.navigateTo({ url: "/pages/search/index" });
    if (p === "/about/intro") return Taro.navigateTo({ url: "/pages/about-intro/index" });
    if (p === "/about/structure") return Taro.navigateTo({ url: "/pages/about-structure/index" });
    if (p.startsWith("/pages/")) return Taro.navigateTo({ url: p });
    if (p.startsWith("http://") || p.startsWith("https://")) {
      void Taro.setClipboardData({ data: p });
      return Taro.showToast({ title: "链接已复制到剪贴板", icon: "none" });
    }
    if (!p) return Taro.showToast({ title: "暂无跳转链接", icon: "none" });
    Taro.showToast({ title: "暂不支持该跳转路径", icon: "none" });
  };

  const gotoModule = (path: string) => gotoPath(path);

  const gotoBanner = (banner: HomeBanner) => {
    const link = String(banner?.link_url || "").trim();
    void gotoPath(link);
  };

  const gotoMediaMatrix = () => Taro.navigateTo({ url: "/pages/media-matrix/index" });

  const gotoBranch = (branchId: number) => {
    void Taro.navigateTo({ url: `/pages/branch-detail/index?id=${branchId}` });
  };

  const gotoGuessCard = (item: GuessCard) => {
    if (item.targetType === "activity" && item.targetId) {
      return Taro.navigateTo({ url: `/pages/activity-detail/index?id=${item.targetId}` });
    }
    if (item.targetType === "content" && item.targetId) {
      return Taro.navigateTo({ url: `/pages/content-detail/index?id=${item.targetId}` });
    }
    return Taro.showToast({ title: "暂无可查看内容", icon: "none" });
  };

  return (
    <View className="page-shell home-page">
      <View className="page-body home-page__body">
        <View className="home-carousel card-surface">
        {homeData?.banners?.length ? (
            <Swiper
              className="home-carousel__swiper"
              circular
              autoplay
              interval={3000}
              duration={500}
              indicatorDots
              indicatorColor="rgba(255,255,255,0.45)"
              indicatorActiveColor="#ffffff"
            >
              {homeData.banners.map((banner: HomeBanner) => (
                <SwiperItem key={banner.id}>
                  <View className="home-carousel__item" onClick={() => gotoBanner(banner)}>
                    {banner.image_url ? (
                      <Image className="home-carousel__image" src={resolveMediaUrl(banner.image_url)} mode="aspectFill" />
                    ) : (
                      <View className="home-carousel__placeholder">
                        <Text>{loading ? "加载中..." : "暂无轮播图数据"}</Text>
                      </View>
                    )}
                    <View className="home-carousel__mask" />
                    <View className="home-carousel__content">
                      <Text className="home-carousel__title">{banner.title || ""}</Text>
                    </View>
                  </View>
                </SwiperItem>
              ))}
            </Swiper>
          ) : (
            <View className="home-carousel__placeholder">
              <Text>{loading ? "加载中..." : "暂无轮播图数据"}</Text>
            </View>
          )}
        </View>

        {error ? (
          <View className="home-error">
            <Text>{error}</Text>
          </View>
        ) : null}

        <View className="home-grid">
          {modules.map((item) => (
            <View key={item.code} className="home-grid__item" onClick={() => gotoModule(item.path || "")}>
              <View className={`home-grid__icon home-grid__icon--${item.code}`}>
                <Image className="home-grid__icon-image" src={(item as any).iconSrc} mode="aspectFit" />
              </View>
              <Text className="home-grid__label">{item.name}</Text>
            </View>
          ))}
        </View>

          <View className="home-branches">
            <View className="section-title-row">
              <Text className="section-title">分会导航</Text>
              <Text className="section-link" onClick={() => setShowAllBranches((prev) => !prev)}>
                {showAllBranches ? "收起" : "更多 >"}
              </Text>
            </View>
          <View className="home-branches__grid">
            {visibleBranches.length > 0 ? (
              visibleBranches.map((item) => (
                <View key={item.id} className="home-branches__item" onClick={() => gotoBranch(item.id)}>
                  <Text className="home-branches__name">{item.name}</Text>
                </View>
              ))
            ) : (
              <Text className="home-empty-text">暂无分会数据</Text>
            )}
          </View>
        </View>

        {mediaAccounts.length > 0 ? (
          <View className="home-media card-surface">
            <View className="home-media__content">
              <Text className="home-media__eyebrow">MEDIA MATRIX</Text>
              <Text className="home-media__title">大连市新联会新媒体矩阵</Text>
              <Text className="home-media__desc">一键查看公众号、视频号、抖音等官方阵地</Text>
              <View className="home-media__icons">
                {mediaPreview.map((item) => (
                  <View key={item.platformKey} className="media-icon">
                    <Image className="media-icon__image" src={item.logoSrc} mode="aspectFit" />
                  </View>
                ))}
              </View>
            </View>
            <View className="home-media__button" onClick={gotoMediaMatrix}>
              <Text className="home-media__button-text">查看</Text>
            </View>
          </View>
        ) : null}

        <View className="home-guess">
          <Text className="section-title">猜你喜欢</Text>
          <View className="home-guess__list">
            {guessCards.length > 0 ? (
              guessCards.map((item, index) => (
                <View key={`${item.targetType}-${item.targetId || index}`} className="home-guess__card card-surface" onClick={() => gotoGuessCard(item)}>
                  <View className="home-guess__cover">
                    {item.coverImageUrl ? (
                      <Image className="home-guess__cover-image" src={item.coverImageUrl} mode="aspectFill" />
                    ) : (
                      <View className="home-guess__cover-empty">
                        <Text>暂无图片</Text>
                      </View>
                    )}
                  </View>
                  <View className="home-guess__body">
                    <View>
                      <Text className="home-guess__category">{getGuessCategoryText(item)}</Text>
                      <Text className="home-guess__title">{item.title || "暂无数据"}</Text>
                    </View>
                    {item.targetType === "activity" ? (
                      <View className="home-guess__meta">
                        <Text className="home-guess__meta-text">
                          已报名：{item.registrationCount || 0}/{item.capacity || 0}人
                        </Text>
                        <Text className="home-guess__action-pill">{item.actionText || "报名"}</Text>
                      </View>
                    ) : (
                      <View className="home-guess__meta">
                        <Text className="home-guess__meta-text">{item.sourceName || `学习：${item.viewCount || 0}人`}</Text>
                        <Text className="home-guess__date">{formatDate(item.startsAt)}</Text>
                      </View>
                    )}
                  </View>
                </View>
              ))
            ) : (
              <Text className="home-empty-text">暂无推荐内容</Text>
            )}
          </View>
        </View>
      </View>
    </View>
  );
}
