import { Button, Image, Text, View } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import { useState } from "react";
import { addFriendByPassport, getPassportCard } from "../../api/social";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import { firstText, resolveMediaUrl } from "../../utils/media";
import "../passport/index.scss";
import "./index.scss";

function normalizePassportId(raw: string) {
  const decoded = decodeURIComponent(raw || "");
  const marker = "/passport/";
  const idx = decoded.indexOf(marker);
  if (idx >= 0) {
    return decoded.slice(idx + marker.length).split(/[?#&]/)[0];
  }
  const match = decoded.match(/passportId=([^&#]+)/i);
  if (match) return decodeURIComponent(match[1]);
  return decoded.replace(/^xlh:\/\/passport\//, "").trim();
}

function relationshipText(value: any) {
  const raw = String(value || "none");
  const map: Record<string, string> = {
    self: "我的通行证",
    friend: "已是好友",
    pending: "已申请",
    pending_sent: "已申请",
    pending_received: "待处理",
    not_member: "暂不可添加"
  };
  return map[raw] || "添加好友";
}

export default function PassportDetailPage() {
  useAuthGuard();
  useMemberGuard("通行证名片仅面向正式会员开放");
  const router = useRouter();
  const [card, setCard] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");

  const passportId = normalizePassportId(String(router.params?.passportId || router.params?.payload || ""));

  const load = async () => {
    if (!passportId) return;
    setLoading(true);
    try {
      const data = await getPassportCard(passportId);
      setCard(data || null);
      setError("");
    } catch (e: any) {
      setError(e?.message || "通行证名片加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const addFriend = async () => {
    if (!passportId || submitting) return;
    setSubmitting(true);
    try {
      await addFriendByPassport(passportId);
      Taro.showToast({ title: "好友申请已发送", icon: "none" });
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "申请失败", icon: "none" });
    } finally {
      setSubmitting(false);
    }
  };

  const status = String(card?.relationshipStatus || card?.relationship_status || card?.friendshipStatus || card?.friendship_status || "none");
  const canAdd = card?.canAddFriend !== false && !["self", "friend", "pending", "pending_sent", "not_member"].includes(status);
  const avatar = resolveMediaUrl(firstText(card?.avatar_url, card?.avatarUrl, card?.avatar));
  const tagText = firstText(card?.tag_names, card?.label_names, card?.branch_names);
  const tags = tagText.split(/[\/,，]/).map((item) => item.trim()).filter(Boolean);

  return (
    <View className="passport-page">
      <View className="passport-page__body">
        {error ? <Text className="passport-state is-error">{error}</Text> : null}
        {loading ? <Text className="passport-state">加载中...</Text> : null}
        {card ? (
          <View className="passport-profile">
            <View className="passport-profile__avatar">
              {avatar ? <Image className="passport-profile__avatar-img" src={avatar} mode="aspectFill" /> : <Text>{String(card.display_name || card.displayName || card.name || "会").slice(0, 1)}</Text>}
            </View>
            <Text className="passport-profile__name">{card.display_name || card.displayName || card.name || "会员"}</Text>
            <Text className="passport-profile__meta">{card.position || card.title || "未填写职务"} · {card.unit || card.organization || "未填写单位"}</Text>
            <Text className="passport-profile__id">{card.passportId || card.passport_id || passportId}</Text>
            <View className="passport-profile__tags">
              {tags.length ? tags.slice(0, 8).map((tag) => <Text key={tag}>{tag}</Text>) : <Text>暂无标签</Text>}
            </View>
            <Text className="passport-profile__intro">{card.intro || card.bio || "暂无简介"}</Text>
            <Button className="passport-btn" disabled={!canAdd || submitting} loading={submitting} onClick={() => void addFriend()}>
              {relationshipText(status)}
            </Button>
          </View>
        ) : !loading && !error ? <Text className="passport-state">通行证不存在或已失效</Text> : null}
      </View>
    </View>
  );
}
