import { Button, Input, Text, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import { useState } from "react";
import { blockUser, createFriendGroup, deleteFriendGroup, getBlockedUsers, getFriendGroups, unblockUser } from "../../api/social";
import { useAuthGuard } from "../../hooks/useAuthGuard";
import { useMemberGuard } from "../../hooks/useMemberGuard";
import "./index.scss";

export default function SocialSettingsPage() {
  useAuthGuard();
  useMemberGuard("社交设置仅面向正式会员开放");

  const [groups, setGroups] = useState<any[]>([]);
  const [blocks, setBlocks] = useState<any[]>([]);
  const [groupName, setGroupName] = useState("");
  const [blockTargetId, setBlockTargetId] = useState("");
  const [loading, setLoading] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  const load = async () => {
    setLoading(true);
    try {
      const [groupData, blockData] = await Promise.all([getFriendGroups().catch(() => []), getBlockedUsers().catch(() => [])]);
      setGroups(Array.isArray(groupData) ? groupData : []);
      setBlocks(Array.isArray(blockData) ? blockData : []);
      setError("");
    } catch (e: any) {
      setError(e?.message || "社交设置加载失败");
    } finally {
      setLoading(false);
    }
  };

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

  const createGroup = async () => {
    const name = groupName.trim();
    if (!name || busy) return;
    setBusy(true);
    try {
      await createFriendGroup({ name });
      setGroupName("");
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "创建失败", icon: "none" });
    } finally {
      setBusy(false);
    }
  };

  const removeGroup = async (id: number) => {
    if (!id || busy) return;
    setBusy(true);
    try {
      await deleteFriendGroup(id);
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "删除失败", icon: "none" });
    } finally {
      setBusy(false);
    }
  };

  const addBlock = async () => {
    const targetId = Number(blockTargetId);
    if (!targetId || busy) {
      Taro.showToast({ title: "请输入用户ID", icon: "none" });
      return;
    }
    setBusy(true);
    try {
      await blockUser(targetId, "小程序社交设置加入黑名单");
      setBlockTargetId("");
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "加入黑名单失败", icon: "none" });
    } finally {
      setBusy(false);
    }
  };

  const removeBlock = async (targetId: number) => {
    if (!targetId || busy) return;
    setBusy(true);
    try {
      await unblockUser(targetId);
      await load();
    } catch (e: any) {
      Taro.showToast({ title: e?.message || "解除失败", icon: "none" });
    } finally {
      setBusy(false);
    }
  };

  return (
    <View className="social-settings-page">
      <View className="social-settings-page__body">
        {error ? <Text className="social-settings-state is-error">{error}</Text> : null}
        {loading ? <Text className="social-settings-state">加载中...</Text> : null}

        <View className="social-settings-panel">
          <Text className="social-settings-title">好友分组</Text>
          <View className="social-settings-form">
            <Input className="social-settings-input" value={groupName} onInput={(e) => setGroupName(e.detail.value)} placeholder="分组名称" placeholderStyle="color:#9ca3af;" />
            <Button className="social-settings-button" loading={busy} onClick={() => void createGroup()}>新增</Button>
          </View>
          {groups.length === 0 ? <Text className="social-settings-empty">暂无分组</Text> : null}
          {groups.map((group) => (
            <View key={group.id || group.name} className="social-settings-row">
              <View>
                <Text className="social-settings-row__title">{group.name || group.group_name || "分组"}</Text>
                <Text className="social-settings-row__meta">{group.memberCount || group.member_count || 0} 人</Text>
              </View>
              <Text className="social-settings-row__link" onClick={() => void removeGroup(Number(group.id))}>删除</Text>
            </View>
          ))}
        </View>

        <View className="social-settings-panel">
          <Text className="social-settings-title">黑名单</Text>
          <View className="social-settings-form">
            <Input className="social-settings-input" value={blockTargetId} type="number" onInput={(e) => setBlockTargetId(e.detail.value)} placeholder="输入用户ID" placeholderStyle="color:#9ca3af;" />
            <Button className="social-settings-button social-settings-button--danger" loading={busy} onClick={() => void addBlock()}>加入</Button>
          </View>
          {blocks.length === 0 ? <Text className="social-settings-empty">暂无黑名单用户</Text> : null}
          {blocks.map((item) => {
            const targetId = Number(item.userId || item.user_id || item.id || item.blockedUserId || item.blocked_user_id);
            return (
              <View key={targetId || item.name} className="social-settings-row">
                <View>
                  <Text className="social-settings-row__title">{item.name || item.displayName || item.display_name || `用户 ${targetId}`}</Text>
                  <Text className="social-settings-row__meta">{item.unit || item.position || "已屏蔽"}</Text>
                </View>
                <Text className="social-settings-row__link" onClick={() => void removeBlock(targetId)}>解除</Text>
              </View>
            );
          })}
        </View>
      </View>
    </View>
  );
}
