import { Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { apiRequest } from "../../api/client";
import { getMyLabels } from "../../api/labels";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useUserStore } from "../../store/user";
import { clearRuntimeCachePreserveLogin } from "../../utils/cache";
import { setSocialDefaultTab } from "../../utils/navFlags";
import "./index.scss";

type NavItem = {
  title: string;
  url?: string;
  action?: () => void | Promise<void>;
};

type ProfileCard = {
  title: string;
  actions?: NavItem[];
  action?: () => void | Promise<void>;
  url?: string;
  art?: "survey" | "join";
};

function isMember(status?: string) {
  return status === "active";
}

function renderBranchTags(branches?: Array<{ name?: string }>) {
  return (branches || []).map((item) => item?.name).filter(Boolean).slice(0, 4) as string[];
}

function extractLabelNames(payload: any): string[] {
  const source = payload?.items || payload?.labelItems || payload?.labels || payload?.data || payload;
  if (!Array.isArray(source)) return [];
  return source
    .map((item: any) => String(item?.name || item?.label_name || item?.labelName || item?.itemName || "").trim())
    .filter(Boolean);
}

function maskPhoneForCard(value?: string) {
  if (!value) return "-";
  if (value.includes("*")) return value;
  return value.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}

function displayName(me: any) {
  const nickname = String(me?.nickname || "").trim();
  if (nickname) return nickname;
  const phone = me?.phoneMasked || me?.phone || "";
  if (phone) return maskPhoneForCard(phone);
  return "用户名";
}

function memberTitle(me: any) {
  const status = String(me?.memberStatus || "").toLowerCase();
  if (!isMember(status)) {
    if (status === "pending" || status === "pending_city_review" || status === "pending_branch_review") return "入会审核中";
    if (status === "returned") return "入会待补充";
    if (status === "rejected" || status === "branch_rejected" || status === "city_rejected") return "申请可重提";
    if (status === "draft") return "入会草稿";
    return "普通用户";
  }
  const type = String(me?.memberType || me?.membershipType || "").toLowerCase();
  if (type.includes("city")) return "市级会员";
  if (type.includes("branch") || type.includes("district")) return "分会会员";
  return "会员";
}

function joinCardTitle(status?: string) {
  const value = String(status || "").toLowerCase();
  if (value === "pending" || value === "pending_city_review" || value === "pending_branch_review") return "查看入会进度";
  if (value === "returned") return "补充入会材料";
  if (value === "rejected" || value === "branch_rejected" || value === "city_rejected") return "重新提交申请";
  if (value === "draft") return "继续入会申请";
  return "加入会员";
}

function idText(me: any) {
  return `ID ${me?.userId || me?.id || "7765432"}`;
}

function shortCount(value: number) {
  if (value > 9999) return `${Math.floor(value / 1000) / 10}万`;
  return String(value);
}

export default function ProfilePage() {
  useAuthGuard();

  const me = useUserStore((state) => state.me);
  const bootstrap = useUserStore((state) => state.bootstrap);

  const [friends, setFriends] = useState<any[]>([]);
  const [myLabels, setMyLabels] = useState<string[]>([]);

  const loadPageData = async () => {
    try {
      const [_, friendData, labelsData] = await Promise.all([
        bootstrap(),
        apiRequest("/api/me/friends"),
        getMyLabels().catch(() => null)
      ]);
      setFriends(Array.isArray(friendData) ? friendData : []);
      setMyLabels(extractLabelNames(labelsData));
    } catch {
      setFriends([]);
      setMyLabels([]);
    }
  };

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

  const gotoFriendRequests = async () => {
    setSocialDefaultTab("inbox");
    await Taro.switchTab({ url: "/pages/social/index" });
  };

  const gotoSocial = async () => {
    await Taro.navigateTo({ url: "/pages/social-card/index" });
  };

  const gotoPoints = async () => {
    await Taro.navigateTo({ url: "/pages/my-points/index" });
  };

  const gotoEditProfile = async () => {
    await Taro.navigateTo({ url: "/pages/profile-edit/index" });
  };

  const gotoMySurveys = async () => {
    await Taro.navigateTo({ url: "/pages/my-surveys/index" });
  };

  const clearCache = async () => {
    const result = await Taro.showModal({
      title: "清理缓存",
      content: "将清理页面草稿、AI会话缓存、临时选择和本地状态，不会退出当前账号。",
      confirmText: "清理",
      cancelText: "取消"
    });
    if (!result.confirm) return;
    const removed = clearRuntimeCachePreserveLogin();
    await bootstrap().catch(() => undefined);
    Taro.showToast({ title: removed ? "缓存已清理" : "暂无可清理缓存", icon: "none" });
  };

  const openNav = (item: NavItem | ProfileCard) => {
    if (item.action) {
      void item.action();
      return;
    }
    if (item.url) void Taro.navigateTo({ url: item.url });
  };

  const renderAction = (item: NavItem) => (
    <View key={item.title} className="profile-pill-action" onClick={() => openNav(item)}>
      <Text>{item.title}</Text>
    </View>
  );

  const renderCard = (card: ProfileCard) => (
    <View key={card.title} className={card.art ? `profile-proto-card has-art ${card.art}` : "profile-proto-card"} onClick={() => openNav(card)}>
      <Text className="profile-card-title">{card.title}</Text>
      {card.actions?.length ? (
        <View className="profile-card-actions">
          {card.actions.map(renderAction)}
        </View>
      ) : null}
      {card.art ? <View className="profile-card-art" /> : null}
      {!card.actions?.length ? (
        <View className="profile-card-circle-arrow">
          <Text>&gt;</Text>
        </View>
      ) : null}
    </View>
  );

  const isMemberUser = isMember(me?.memberStatus);
  const joinTitle = joinCardTitle(me?.memberStatus);
  const points = Number(me?.points || 0);
  const unreadCount = Number(me?.unreadCount || me?.unread_count || 0);
  const name = displayName(me);
  const tags = (myLabels.length > 0 ? myLabels : renderBranchTags(me?.branches)).slice(0, 6);
  const contactValue = maskPhoneForCard(me?.phoneMasked || me?.phone);
  const friendCountText = friends.length ? `关系连接${friends.length}` : "关系连接0";
  const accountSettingCard: ProfileCard = {
    title: "账号设置",
    actions: [
      { title: "资料设置", action: gotoEditProfile },
      { title: "账号安全", url: "/pages/account-security/index" },
      { title: "清理缓存", action: clearCache }
    ]
  };

  const guestCards: ProfileCard[] = [
    accountSettingCard,
    {
      title: "我的浏览",
      actions: [
        { title: "新闻资讯", url: "/pages/my-browsing-history/index" },
        { title: "学习记录", url: "/pages/my-learning/index" }
      ]
    },
    {
      title: "我的活动",
      actions: [
        { title: "我发布的活动", url: "/pages/my-created-activities/index" },
        { title: "我报名的活动", url: "/pages/my-registered-activities/index" }
      ]
    },
    { title: "我参与的调查", art: "survey", action: gotoMySurveys },
    { title: joinTitle, art: "join", url: "/pages/join/index" }
  ];

  const memberCards: ProfileCard[] = [
    accountSettingCard,
    {
      title: "我的履职",
      actions: [
        { title: "学习记录", url: "/pages/my-learning/index" },
        { title: "我的建言", url: "/pages/my-suggestions/index" },
        { title: "社会服务项目", url: "/pages/my-service-projects/index" },
        { title: "成就档案", url: "/pages/evaluation/index" }
      ]
    },
    {
      title: "我的活动",
      actions: [
        { title: "我发布的活动", url: "/pages/my-created-activities/index" },
        { title: "我报名的活动", url: "/pages/my-registered-activities/index" }
      ]
    },
    { title: "我参与的调查", art: "survey", action: gotoMySurveys },
    {
      title: "企业互助",
      actions: [
        { title: "我发布的资源", url: "/pages/my-mutual-aid-resources/index" },
        { title: "我发布的需求", url: "/pages/my-mutual-aid-needs/index" }
      ]
    },
    {
      title: "社交管理",
      actions: [
        { title: "我的名片", url: "/pages/social-card/index" },
        { title: "新联会通行证", url: "/pages/passport/index" },
        { title: "社交设置", url: "/pages/social-settings/index" }
      ]
    },
    {
      title: "连小新",
      actions: [
        { title: "待确认", url: "/pages/ai-approvals/index" },
        { title: "授权范围", url: "/pages/ai-grants/index" }
      ]
    }
  ];

  return (
    <View className="page-shell profile-page">
      <View className="profile-page__body">
        <View className="profile-user-band">
          <View className="profile-user-row">
            <View className="profile-avatar">
              {me?.avatarUrl ? (
                <Image className="profile-avatar__image" src={me.avatarUrl} mode="aspectFill" />
              ) : (
                <View className="profile-avatar__fallback">
                  <View className="profile-avatar__head" />
                  <View className="profile-avatar__body" />
                </View>
              )}
            </View>
            <View className="profile-user-main">
              <View className="profile-name-row">
                <Text className="profile-name">{name}</Text>
                <Text className={isMemberUser ? "profile-role-badge" : "profile-role-badge muted"}>{memberTitle(me)}</Text>
              </View>
              <Text className="profile-id">{idText(me)}</Text>
            </View>
            <View className="profile-edit" onClick={() => void gotoEditProfile()}>
              <Text>编辑</Text>
            </View>
          </View>

          <View className="profile-point-row">
            <View className="profile-point-pill">
              <Text>积分：{shortCount(points)}</Text>
            </View>
            <View className="profile-point-btn" onClick={() => void gotoPoints()}>
              <Text>我的积分</Text>
            </View>
            <View className={unreadCount > 0 ? "profile-message-btn has-unread" : "profile-message-btn"} onClick={() => Taro.navigateTo({ url: "/pages/notifications/index" })}>
              <Text>{unreadCount > 0 ? `消息 ${shortCount(unreadCount)}` : "消息通知"}</Text>
            </View>
          </View>
        </View>

        {isMemberUser ? (
          <View className="profile-social-card">
            <View className="profile-social-head">
              <View className="profile-social-title-row">
                <Text className="profile-social-title">我的社交圈</Text>
                <Text className="profile-social-relation">{friendCountText}</Text>
              </View>
              <Text className="profile-social-edit" onClick={() => void gotoSocial()}>编辑</Text>
            </View>
            <View className="profile-social-actions">
              <View className="profile-contact-pill">
                <Text>联系电话/微信：{contactValue}</Text>
              </View>
              <View className="profile-friend-btn" onClick={() => void gotoFriendRequests()}>
                <Text>我的好友</Text>
              </View>
            </View>
            <View className="profile-tag-list">
              {(tags.length ? tags : ["应用软件", "云计算", "网络安全", "音乐", "运动健身", "旅行"]).map((tag) => (
                <Text key={tag} className="profile-tag">{tag}</Text>
              ))}
            </View>
          </View>
        ) : null}

        <View className="profile-card-grid">
          {(isMemberUser ? memberCards : guestCards).map(renderCard)}
        </View>

        <View className="profile-footer">
          <Text>邮箱：elianxin@126.com</Text>
          <Text>地址：大连市中山区XX号XX室</Text>
          <Text>版权所有 大连市新的社会阶层人士联谊会</Text>
        </View>
      </View>
    </View>
  );
}
