import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { getMyLabels } from "../../api/labels";
import { getMyProfile } from "../../api/me";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { useUserStore } from "../../store/user";
import { selectedCustomLabels, selectedInterestNames, selectedProfessionalNames } from "../../utils/labels";
import { setSocialDefaultTab } from "../../utils/navFlags";
import "./index.scss";

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

function displayName(form: any) {
  const name = String(form?.displayName || "").trim();
  if (name) return name;
  return "未命名用户";
}

export default function SocialCardPage() {
  useAuthGuard();
  useMemberGuard("我的名片仅面向正式会员开放");

  const me = useUserStore((state) => state.me);
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState<any>({
    displayName: "",
    avatarUrl: "",
    unit: "",
    position: "",
    phoneMasked: "",
    intro: ""
  });
  const [myLabels, setMyLabels] = useState<string[]>([]);
  const [interestLabels, setInterestLabels] = useState<string[]>([]);

  useDidShow(() => {
    void (async () => {
      setLoading(true);
      try {
        const [data, labelsData] = await Promise.all([getMyProfile(), getMyLabels().catch(() => null)]);
        setForm({
          displayName: data?.displayName || data?.name || data?.nickname || "",
          avatarUrl: data?.avatarUrl || data?.avatar || "",
          unit: data?.unit || "",
          position: data?.position || "",
          phoneMasked: data?.phoneMasked || data?.phone || "",
          intro: data?.intro || ""
        });
        setMyLabels([...selectedProfessionalNames(labelsData), ...selectedCustomLabels(labelsData)]);
        setInterestLabels(selectedInterestNames(labelsData));
      } catch (e: any) {
        Taro.showToast({ title: e?.message || "名片加载失败", icon: "none" });
        setForm({
          displayName: "",
          avatarUrl: "",
          unit: "",
          position: "",
          phoneMasked: "",
          intro: ""
        });
        setMyLabels([]);
        setInterestLabels([]);
      } finally {
        setLoading(false);
      }
    })();
  });

  const professionalLabels = (Array.isArray(myLabels) ? myLabels : [])
    .map((x) => String(x || "").trim())
    .filter(Boolean);
  const displayTags = professionalLabels.slice(0, 8);

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

  const gotoSelectTags = async () => {
    await Taro.navigateTo({ url: "/pages/tag-select/index" });
  };

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

  const name = displayName(form);
  const memberText = me?.memberStatus === "active" ? "会员" : "普通用户";

  return (
    <View className="page-shell social-card-page">
      <View className="page-body social-card-page__body">
        <View className="card-surface social-card-box">
          <View className="social-card-deco social-card-deco--top" />
          <View className="social-card-deco social-card-deco--bottom" />

          <View className="social-card-inner">
            <View className="social-card-header">
              <View className="social-card-header__left">
                <View className="social-card-avatar">
                  {form.avatarUrl ? (
                    <Image className="social-card-avatar__img" src={form.avatarUrl} mode="aspectFill" />
                  ) : (
                    <View className="social-card-avatar__fallback">
                      <Text>{name.slice(0, 1)}</Text>
                    </View>
                  )}
                </View>

                <View className="social-card-name">
                  <Text className="social-card-name__main">{name}</Text>
                  <Text className="social-card-name__sub">{form.unit || form.position || "暂无单位信息"}</Text>
                  <View className="social-card-name__meta">
                    <Text className="social-card-badge">{memberText}</Text>
                    <Text className="social-card-id">ID {me?.userId || "-"}</Text>
                  </View>
                </View>
              </View>

              <View className="social-card-edit" onClick={() => void gotoEditProfile()}>
                <Text className="social-card-edit__icon">✎</Text>
              </View>
            </View>

            <View className="social-card-contact">
              <View className="social-card-contact__info">
                <Text className="social-card-contact__label">联系电话/微信</Text>
                <Text className="social-card-contact__value">{maskPhone(form.phoneMasked)}</Text>
              </View>
              <Button className="social-card-contact__btn" size="mini" onClick={() => void gotoSelectTags()}>
                选择标签
              </Button>
            </View>

            <View className="social-card-section">
              <Text className="social-card-section__title">兴趣标签</Text>
              <View className="social-card-tags">
                {interestLabels.length > 0 ? (
                  interestLabels.slice(0, 8).map((tag: string) => (
                    <Text key={tag} className="social-card-tag">
                      {tag}
                    </Text>
                  ))
                ) : (
                  <Text className="social-card-empty">{loading ? "加载中..." : "暂无兴趣"}</Text>
                )}
              </View>
            </View>

            <View className="social-card-section">
              <Text className="social-card-section__title">专业标签</Text>
              <View className="social-card-tags">
                {displayTags.length > 0 ? (
                  displayTags.map((tag: string) => (
                    <Text key={tag} className="social-card-tag">
                      {tag}
                    </Text>
                  ))
                ) : (
                  <Text className="social-card-empty">{loading ? "加载中..." : "暂无标签"}</Text>
                )}
              </View>
            </View>

            <View className="social-card-section social-card-section--intro">
              <Text className="social-card-section__title">个人简介</Text>
              <View className="social-card-intro">
                <Text>{form.intro || "暂无数据"}</Text>
              </View>
            </View>

            <Button className="social-card-friends" onClick={() => void gotoFriends()}>
              我的好友
            </Button>
          </View>
        </View>
      </View>
    </View>
  );
}
