import { Button, Image, ScrollView, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useEffect, useMemo, useState } from "react";
import { apiRequest } from "../../api/client";
import { getLabelDictionary, saveMyLabels } from "../../api/labels";
import { acceptFriend, getFriendInbox, getFriendOutbox, getSocialMembers, rejectFriend } from "../../api/social";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { ensureMemberAccess } from "../../utils/permission";
import {
  dedupe,
  interestItems,
  MAX_INTEREST_LABELS,
  professionalCategories,
  selectedCustomLabels as selectedCustomLabelsOf,
  selectedInterestIds as selectedInterestIdsOf,
  selectedProfessionalIds
} from "../../utils/labels";
import { takeSocialDefaultStep, takeSocialDefaultTab } from "../../utils/navFlags";
import "./index.scss";

type TagItem = {
  id: number;
  name: string;
  type?: string;
  code?: string;
};

type MemberItem = {
  user_id?: number;
  userId?: number;
  id?: number;
  display_name?: string;
  displayName?: string;
  nickname?: string;
  unit?: string;
  position?: string;
  expertise?: string;
  tag_names?: string;
  branch_names?: string;
  avatar_url?: string;
};

type FriendRequestItem = {
  id: number;
  status: string;
  user_id?: number;
  userId?: number;
  display_name?: string;
  displayName?: string;
  nickname?: string;
  unit?: string;
  position?: string;
  expertise?: string;
  avatar_url?: string;
};

function getUserId(item: any) {
  return item?.user_id || item?.userId || item?.id || 0;
}

function getDisplayName(item: any) {
  return item?.display_name || item?.displayName || item?.nickname || `会员${getUserId(item)}`;
}

function getPosition(item: any) {
  return item?.position || item?.unit || "暂无职务";
}

function getIntro(item: any) {
  return item?.unit || item?.position || "欢迎交流合作";
}

function getAvatar(item: any) {
  return item?.avatar_url || "";
}

function getTagList(item: any) {
  return (item?.tag_names || item?.expertise || "")
    .split(/[\/,，]/)
    .map((value: string) => value.trim())
    .filter(Boolean)
    .slice(0, 6);
}

function getBranchName(item: any) {
  const branch = (item?.branch_names || "")
    .split("/")
    .map((value: string) => value.trim())
    .filter(Boolean)[0];
  return branch || "全部";
}

function statusText(status: string) {
  if (status === "pending") return "待处理";
  if (status === "accepted") return "已通过";
  if (status === "rejected") return "已拒绝";
  return status || "-";
}

function friendStatusOf(item: any) {
  const status = String(item?.friendship_status || item?.friendshipStatus || item?.status || "").trim();
  if (status === "accepted") return "friend";
  if (status === "friend" || status === "pending" || status === "incoming") return status;
  return "none";
}

function friendActionText(status: string) {
  if (status === "none") return "+ 好友";
  if (status === "pending") return "等待通过";
  if (status === "incoming") return "待处理";
  return "已是好友";
}

function TagSelection({ onNext }: { onNext: () => void }) {
  const [allTags, setAllTags] = useState<TagItem[]>([]);
  const [dictCategories, setDictCategories] = useState<Array<{ id: number; name: string; code?: string; items: Array<{ id: number; name: string; code?: string }> }>>([]);
  const [interestTags, setInterestTags] = useState<Array<{ id: number; name: string; code?: string }>>([]);
  const [selectedInterestIds, setSelectedInterestIds] = useState<number[]>([]);
  const [selectedItemIds, setSelectedItemIds] = useState<number[]>([]);
  const [selectedCustomLabels, setSelectedCustomLabels] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    const loadTags = async () => {
      try {
        const [dict, mine] = await Promise.all([getLabelDictionary(), apiRequest("/api/labels/me") as Promise<any>]);
        const normalizedCategories = professionalCategories(dict);
        setDictCategories(normalizedCategories);
        setInterestTags(interestItems(dict));

        const flat = normalizedCategories.flatMap((cat: any) =>
          cat.items.map((item: any) => ({
            id: Number(item.id),
            name: String(item.name),
            type: String(cat.code || cat.name || ""),
            code: String(item.code || "")
          }))
        );
        setAllTags(flat);

        setSelectedInterestIds(selectedInterestIdsOf(mine));
        setSelectedItemIds(selectedProfessionalIds(mine));
        setSelectedCustomLabels(dedupe(selectedCustomLabelsOf(mine)));
        setError("");
      } catch (e: any) {
        setError(e?.message || "标签加载失败");
      }
    };
    void loadTags();
  }, []);

  const professionalNames = useMemo(() => {
    const map = new Map<number, string>();
    allTags.forEach((item) => map.set(item.id, item.name));
    const fromDict = selectedItemIds.map((id) => map.get(id) || "").filter(Boolean);
    return Array.from(new Set([...fromDict, ...selectedCustomLabels]));
  }, [allTags, selectedItemIds, selectedCustomLabels]);

  const openProfessionalPage = async () => {
    const draftKey = `social_prof_draft_${Date.now()}`;
    Taro.setStorageSync(draftKey, {
      categories: dictCategories,
      selectedItemIds,
      selectedCustomLabels
    });
    await Taro.navigateTo({
      url: `/pages/tag-professional/index?draftKey=${encodeURIComponent(draftKey)}`,
      success: (res) => {
        res.eventChannel.on("professionalSelectionSaved", (payload: { selectedItemIds: number[]; selectedCustomLabels: string[] }) => {
          setSelectedItemIds(Array.isArray(payload?.selectedItemIds) ? payload.selectedItemIds : []);
          setSelectedCustomLabels(Array.isArray(payload?.selectedCustomLabels) ? payload.selectedCustomLabels : []);
        });
      }
    });
  };

  const saveTags = async () => {
    if (saving) return;
    setSaving(true);
    try {
      await saveMyLabels(selectedInterestIds, [], "interest");
      await saveMyLabels(selectedItemIds, dedupe(selectedCustomLabels), "professional");
      onNext();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "保存标签失败", icon: "none" });
    } finally {
      setSaving(false);
    }
  };

  const toggleInterest = (id: number) => {
    setSelectedInterestIds((prev) => {
      if (prev.includes(id)) return prev.filter((item) => item !== id);
      if (prev.length >= MAX_INTEREST_LABELS) {
        Taro.showToast({ title: `最多选择${MAX_INTEREST_LABELS}个`, icon: "none" });
        return prev;
      }
      return [...prev, id];
    });
  };

  return (
    <View className="page-shell social-page">
      <View className="page-body social-tag-page">
        <Text className="social-section__title">请选择兴趣标签（{selectedInterestIds.length}/{MAX_INTEREST_LABELS}）</Text>
        {error ? <Text className="social-error">{error}</Text> : null}
        <View className="social-tag-cloud">
          {interestTags.map((item) => (
            <View
              key={item.id}
              className={`social-tag-pill ${selectedInterestIds.includes(item.id) ? "social-tag-pill--active" : ""}`}
              onClick={() => toggleInterest(item.id)}
            >
              <Text>{item.name}</Text>
            </View>
          ))}
          {!interestTags.length ? <Text className="tag-selected-preview__empty">暂无兴趣选项</Text> : null}
        </View>

        <Text className="social-section__title social-section__title--spaced">请选择专业标签</Text>
        <View className="tag-prof-entry" onClick={() => void openProfessionalPage()}>
          <View className="tag-prof-entry__left">
            <Text className="tag-prof-entry__label">专业标签</Text>
            <Text className="tag-prof-entry__hint">{professionalNames.length > 0 ? `已选 ${professionalNames.length} 项` : "请选择"}</Text>
          </View>
          <Text className="tag-prof-entry__arrow">&gt;</Text>
        </View>
        <View className="tag-selected-preview">
          {professionalNames.length > 0 ? (
            professionalNames.slice(0, 12).map((name) => (
              <Text key={name} className="tag-selected-preview__pill">
                {name}
              </Text>
            ))
          ) : (
            <Text className="tag-selected-preview__empty">暂无专业标签</Text>
          )}
        </View>
      </View>

      <View className="social-bottom-bar">
        <Button className="social-primary-btn" loading={saving} onClick={() => void saveTags()}>
          下一步
        </Button>
      </View>
    </View>
  );
}

function RecommendFriends({
  onFinish,
  friendStatuses,
  onToggleFriend
}: {
  onFinish: () => void;
  friendStatuses: Record<number, string>;
  onToggleFriend: (id: number) => Promise<void>;
}) {
  const [members, setMembers] = useState<MemberItem[]>([]);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);

  useEffect(() => {
    void getSocialMembers().then((result) => setMembers(Array.isArray(result) ? result.slice(0, 8) : []));
  }, []);

  const toggleSelect = (id: number) => {
    setSelectedIds((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
  };

  return (
    <View className="page-shell social-page">
      <ScrollView scrollY className="social-recommend">
        <Text className="social-section__title">推荐好友</Text>
        <View className="social-recommend__grid">
          {members.length > 0 ? (
            members.map((item) => {
              const id = getUserId(item);
              const status = friendStatuses[id] || "none";
              const tags = getTagList(item);
              return (
                <View key={id} className="social-recommend__card card-surface">
                  <View className="social-recommend__check" onClick={() => toggleSelect(id)}>
                    <Text>{selectedIds.includes(id) ? "✓" : ""}</Text>
                  </View>
                  <View className="social-recommend__avatar">
                    {getAvatar(item) ? <Image className="social-recommend__avatar-image" src={getAvatar(item)} mode="aspectFill" /> : null}
                  </View>
                  <Text className="social-recommend__name">{getDisplayName(item)}</Text>
                  <View className="social-recommend__tags">
                    {tags.slice(0, 4).map((tag) => (
                      <Text key={tag} className="social-recommend__tag">
                        {tag}
                      </Text>
                    ))}
                  </View>
                  <View className={`social-recommend__add ${status !== "none" ? "social-recommend__add--disabled" : ""}`} onClick={() => {
                    if (status === "none") void onToggleFriend(id);
                  }}>
                    <Text>{friendActionText(status)}</Text>
                  </View>
                </View>
              );
            })
          ) : (
            <View className="social-empty-panel social-empty-panel--grid">
              <Text>暂无推荐会员</Text>
            </View>
          )}
        </View>
      </ScrollView>

      <View className="social-bottom-bar social-bottom-bar--two">
        <Button className="social-primary-btn" onClick={onFinish}>
          确定
        </Button>
        <Button className="social-ghost-btn" onClick={onFinish}>
          跳过
        </Button>
      </View>
    </View>
  );
}

function SocialMain({
  members,
  inbox,
  outbox,
  friendStatuses,
  onToggleFriend,
  onAccept,
  onReject,
  onEditTags,
  initialTab
}: {
  members: MemberItem[];
  inbox: FriendRequestItem[];
  outbox: FriendRequestItem[];
  friendStatuses: Record<number, string>;
  onToggleFriend: (id: number) => Promise<void>;
  onAccept: (id: number) => Promise<void>;
  onReject: (id: number) => Promise<void>;
  onEditTags: () => void;
  initialTab?: "members" | "friends";
}) {
  const [activeTab, setActiveTab] = useState<"members" | "friends">(initialTab || "members");
  const [branchFilter, setBranchFilter] = useState("全部");

  const branches = useMemo(() => {
    const options = Array.from(new Set(members.map((item) => getBranchName(item)).filter(Boolean)));
    return ["全部", ...options];
  }, [members]);

  const filteredMembers = useMemo(() => {
    return members.filter((item) => branchFilter === "全部" || getBranchName(item) === branchFilter);
  }, [members, branchFilter]);

  const acceptedFriends = useMemo(() => {
    return members.filter((item) => friendStatuses[getUserId(item)] === "friend");
  }, [friendStatuses, members]);

  return (
    <View className="page-shell social-page">
      <View className="social-main-head">
        <View className="social-main-head__action" onClick={() => Taro.navigateTo({ url: "/pages/social-settings/index" })}>
          <Text>社交设置</Text>
        </View>
        <View className="social-main-head__action" onClick={onEditTags}>
          <Text>标签管理</Text>
        </View>
      </View>

      <View className="social-tab-switch">
        <View className={`social-tab-switch__item ${activeTab === "members" ? "is-active" : ""}`} onClick={() => setActiveTab("members")}>
          <Text>会员列表</Text>
        </View>
        <View className={`social-tab-switch__item ${activeTab === "friends" ? "is-active" : ""}`} onClick={() => setActiveTab("friends")}>
          <Text>我的好友</Text>
        </View>
      </View>

      {activeTab === "members" ? (
        <>
          <ScrollView scrollX className="social-filter-row">
            {branches.map((item) => (
              <View key={item} className={`social-filter-chip ${branchFilter === item ? "is-active" : ""}`} onClick={() => setBranchFilter(item)}>
                <Text>{item}</Text>
              </View>
            ))}
          </ScrollView>

          <ScrollView scrollY className="social-list">
            {filteredMembers.length > 0 ? (
              filteredMembers.map((item) => {
                const id = getUserId(item);
                const status = friendStatuses[id] || "none";
                const tags = getTagList(item);
                return (
                  <View key={id} className="social-member-card card-surface">
                    <View className="social-member-card__avatar">
                      {getAvatar(item) ? <Image className="social-member-card__avatar-image" src={getAvatar(item)} mode="aspectFill" /> : null}
                    </View>
                    <View className="social-member-card__body">
                      <View className="social-member-card__top">
                        <View>
                          <Text className="social-member-card__name">{getDisplayName(item)}</Text>
                          <Text className="social-member-card__title">{getPosition(item)}</Text>
                        </View>
                        <View
                          className={`social-member-card__action ${status !== "none" ? "social-member-card__action--disabled" : ""}`}
                          onClick={() => {
                            if (status === "none") void onToggleFriend(id);
                          }}
                        >
                          <Text>{friendActionText(status)}</Text>
                        </View>
                      </View>
                      <Text className="social-member-card__intro">{getIntro(item)}</Text>
                      <View className="social-member-card__tags">
                        {tags.map((tag) => (
                          <Text key={tag} className="social-member-card__tag">
                            {tag}
                          </Text>
                        ))}
                      </View>
                    </View>
                  </View>
                );
              })
            ) : (
              <View className="social-empty-panel">
                <Text>当前筛选下暂无会员</Text>
              </View>
            )}
          </ScrollView>
        </>
      ) : (
        <ScrollView scrollY className="social-list">
          {inbox.length > 0 ? (
            <View className="social-request-section">
              <Text className="social-request-section__title">好友申请</Text>
              <View className="social-request-section__list">
                {inbox.map((item) => (
                  <View key={item.id} className="social-request-card card-surface">
                    <View className="social-request-card__avatar">
                      {getAvatar(item) ? <Image className="social-request-card__avatar-image" src={getAvatar(item)} mode="aspectFill" /> : null}
                    </View>
                    <View className="social-request-card__body">
                      <Text className="social-request-card__name">{getDisplayName(item)}</Text>
                      <Text className="social-request-card__title">{getPosition(item)}</Text>
                      <Text className="social-request-card__status">{statusText(item.status)}</Text>
                    </View>
                    {item.status === "pending" ? (
                      <View className="social-request-card__btns">
                        <View className="social-request-card__btn social-request-card__btn--accept" onClick={() => void onAccept(item.id)}>
                          <Text>同意</Text>
                        </View>
                        <View className="social-request-card__btn social-request-card__btn--reject" onClick={() => void onReject(item.id)}>
                          <Text>拒绝</Text>
                        </View>
                      </View>
                    ) : null}
                  </View>
                ))}
              </View>
            </View>
          ) : null}

          <View className="social-request-section">
            <Text className="social-request-section__title">我的好友</Text>
            <View className="social-request-section__list">
              {acceptedFriends.length > 0 ? (
                acceptedFriends.map((item) => (
                  <View key={getUserId(item)} className="social-member-card card-surface">
                    <View className="social-member-card__avatar">
                      {getAvatar(item) ? <Image className="social-member-card__avatar-image" src={getAvatar(item)} mode="aspectFill" /> : null}
                    </View>
                    <View className="social-member-card__body">
                      <View className="social-member-card__top">
                        <View>
                          <Text className="social-member-card__name">{getDisplayName(item)}</Text>
                          <Text className="social-member-card__title">{getPosition(item)}</Text>
                        </View>
                        <View className="social-member-card__action social-member-card__action--disabled">
                          <Text>已是好友</Text>
                        </View>
                      </View>
                      <Text className="social-member-card__intro">{getIntro(item)}</Text>
                      <View className="social-member-card__tags">
                        {getTagList(item).map((tag) => (
                          <Text key={tag} className="social-member-card__tag">
                            {tag}
                          </Text>
                        ))}
                      </View>
                    </View>
                  </View>
                ))
              ) : (
                <Text className="social-empty">暂无好友</Text>
              )}
            </View>
          </View>

          {outbox.length > 0 ? (
            <View className="social-request-section">
              <Text className="social-request-section__title">发出的申请</Text>
              <View className="social-request-section__list">
                {outbox.map((item) => (
                  <View key={item.id} className="social-request-card card-surface">
                    <View className="social-request-card__avatar">
                      {getAvatar(item) ? <Image className="social-request-card__avatar-image" src={getAvatar(item)} mode="aspectFill" /> : null}
                    </View>
                    <View className="social-request-card__body">
                      <Text className="social-request-card__name">{getDisplayName(item)}</Text>
                      <Text className="social-request-card__title">{getPosition(item)}</Text>
                      <Text className="social-request-card__status">{statusText(item.status)}</Text>
                    </View>
                  </View>
                ))}
              </View>
            </View>
          ) : null}
        </ScrollView>
      )}
    </View>
  );
}

export default function SocialPage() {
  useAuthGuard();
  const [step, setStep] = useState<"tags" | "recommend" | "main">("main");
  const [initialTab, setInitialTab] = useState<"members" | "friends">("members");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [members, setMembers] = useState<MemberItem[]>([]);
  const [inbox, setInbox] = useState<FriendRequestItem[]>([]);
  const [outbox, setOutbox] = useState<FriendRequestItem[]>([]);
  const [friendStatuses, setFriendStatuses] = useState<Record<number, string>>({});

  const load = async () => {
    setLoading(true);
    try {
      const memberData = await getSocialMembers();
      const [inboxData, outboxData] = await Promise.all([
        getFriendInbox().catch(() => []),
        getFriendOutbox().catch(() => [])
      ]);
      const memberList = Array.isArray(memberData) ? memberData : [];
      const inboxList = Array.isArray(inboxData) ? inboxData : [];
      const outboxList = Array.isArray(outboxData) ? outboxData : [];
      const statusMap: Record<number, string> = {};

      memberList.forEach((item) => {
        const userId = getUserId(item);
        const status = friendStatusOf(item);
        if (userId && status !== "none") {
          statusMap[userId] = status;
        }
      });

      inboxList.forEach((item) => {
        const userId = getUserId(item);
        if (userId) {
          statusMap[userId] = item.status === "accepted" ? "friend" : item.status === "pending" ? "incoming" : item.status;
        }
      });
      outboxList.forEach((item) => {
        const userId = getUserId(item);
        if (userId) {
          statusMap[userId] = item.status === "accepted" ? "friend" : item.status;
        }
      });

      setMembers(memberList);
      setInbox(inboxList);
      setOutbox(outboxList);
      setFriendStatuses(statusMap);
      setError("");
    } catch (e: any) {
      setError(e?.message || "社交圈加载失败");
    } finally {
      setLoading(false);
    }
  };

  useDidShow(() => {
    const defaultTab = takeSocialDefaultTab();
    const defaultStep = takeSocialDefaultStep();
    if (defaultStep === "tags") {
      setStep("tags");
    } else if (defaultStep === "recommend") {
      setStep("recommend");
    } else {
      setStep("main");
    }
    if (defaultTab === "inbox" || defaultTab === "outbox") {
      setInitialTab("friends");
    } else if (defaultTab === "members") {
      setInitialTab("members");
    }
    void load();
  });

  const onToggleFriend = async (targetUserId: number) => {
    try {
      const ok = await ensureMemberAccess("申请好友仅面向正式会员开放");
      if (!ok) return;
      await apiRequest("/api/social/friendships", {
        method: "POST",
        body: JSON.stringify({ targetUserId })
      });
      Taro.showToast({ title: "申请已发送", icon: "none" });
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "好友申请失败", icon: "none" });
    }
  };

  const onAccept = async (id: number) => {
    try {
      const ok = await ensureMemberAccess("处理好友申请仅面向正式会员开放");
      if (!ok) return;
      await acceptFriend(id);
      Taro.showToast({ title: "已同意", icon: "none" });
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "处理失败", icon: "none" });
    }
  };

  const onReject = async (id: number) => {
    try {
      const ok = await ensureMemberAccess("处理好友申请仅面向正式会员开放");
      if (!ok) return;
      await rejectFriend(id);
      Taro.showToast({ title: "已拒绝", icon: "none" });
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "处理失败", icon: "none" });
    }
  };

  if (step === "tags") {
    return <TagSelection onNext={() => setStep("recommend")} />;
  }

  if (step === "recommend") {
    return <RecommendFriends onFinish={() => setStep("main")} friendStatuses={friendStatuses} onToggleFriend={onToggleFriend} />;
  }

  return (
    <View className="page-shell social-page">
      {error ? (
        <View className="page-body">
          <Text className="social-error">{error}</Text>
        </View>
      ) : null}
      {loading && members.length === 0 ? (
        <View className="page-body">
          <Text className="social-empty">加载中...</Text>
        </View>
      ) : (
        <SocialMain
          members={members}
          inbox={inbox}
          outbox={outbox}
          friendStatuses={friendStatuses}
          onToggleFriend={onToggleFriend}
          onAccept={onAccept}
          onReject={onReject}
          onEditTags={() => setStep("tags")}
          initialTab={initialTab}
        />
      )}
    </View>
  );
}



