import React, { useState, useRef, useEffect, useCallback } from "react";
import { Popup, Button, SearchBar, Checkbox, Avatar, SpinLoading, Empty } from "antd-mobile";
import styles from "./FriendSearchModal.module.scss";
import { getUsersByFilter } from "../api";

interface Friend {
  id: string;
  name: string;
  avatar: string;
  wechatId: string;
  tags: string[];
}

interface FriendSearchModalProps {
  visible: boolean;
  onClose: () => void;
  onConfirm: (friends: Friend[]) => void;
  existingConditions: any[]; // 已有的筛选条件
  selectedFriends?: Friend[]; // 已选中的好友
}

const FriendSearchModal: React.FC<FriendSearchModalProps> = ({
  visible,
  onClose,
  onConfirm,
  existingConditions,
  selectedFriends = [],
}) => {
  const [keyword, setKeyword] = useState("");
  const [loading, setLoading] = useState(false);
  const [friends, setFriends] = useState<Friend[]>([]);
  const [selected, setSelected] = useState<Friend[]>(selectedFriends);
  const [total, setTotal] = useState(0);
  const debounceTimer = useRef<NodeJS.Timeout | null>(null);

  // 初始化已选中的好友
  useEffect(() => {
    if (visible) {
      setSelected(selectedFriends);
      // 自动加载一批数据
      searchFriends("");
    }
  }, [visible, selectedFriends]);

  // 搜索好友
  const searchFriends = useCallback(async (searchKeyword: string) => {
    setLoading(true);
    try {
      // 构造 ruleConfig，包含已有条件
      const conditions = existingConditions.filter(c => c.field !== 'friendIds'); // 排除已有的好友ID条件

      const ruleConfig: any = {
        logic: "AND",
        conditions: conditions,
      };

      // 添加搜索关键词
      if (searchKeyword) {
        ruleConfig.keyword = searchKeyword;
      }

      const result = await getUsersByFilter({
        ruleConfig,
        page: 1,
        pageSize: 50,
      });

      // 转换数据格式
      const friendList: Friend[] = result.list.map((user: any) => ({
        id: String(user.id),
        name: user.nickname || user.wechatId || user.identifier,
        avatar: user.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${user.id}`,
        wechatId: user.wechatId || user.wechatAlias || "",
        tags: Array.isArray(user.tags)
          ? user.tags.map((tag: any) => typeof tag === 'string' ? tag : tag.tagName || '').slice(0, 2)
          : [],
      }));

      setFriends(friendList);
      setTotal(result.total);
    } catch (error) {
      console.error("搜索好友失败:", error);
      setFriends([]);
    } finally {
      setLoading(false);
    }
  }, [existingConditions]);

  // 搜索防抖
  const handleSearch = (value: string) => {
    setKeyword(value);

    if (debounceTimer.current) {
      clearTimeout(debounceTimer.current);
    }

    debounceTimer.current = setTimeout(() => {
      searchFriends(value);
    }, 500);
  };

  // 切换选中状态
  const toggleSelect = (friend: Friend) => {
    setSelected(prev => {
      const exists = prev.find(f => f.id === friend.id);
      if (exists) {
        return prev.filter(f => f.id !== friend.id);
      } else {
        return [...prev, friend];
      }
    });
  };

  // 全选当前页
  const selectAll = () => {
    const newSelected = [...selected];
    friends.forEach(friend => {
      if (!newSelected.find(f => f.id === friend.id)) {
        newSelected.push(friend);
      }
    });
    setSelected(newSelected);
  };

  // 取消全选
  const deselectAll = () => {
    const friendIds = friends.map(f => f.id);
    setSelected(prev => prev.filter(f => !friendIds.includes(f.id)));
  };

  // 确认选择
  const handleConfirm = () => {
    onConfirm(selected);
    onClose();
  };

  // 清理
  useEffect(() => {
    return () => {
      if (debounceTimer.current) {
        clearTimeout(debounceTimer.current);
      }
    };
  }, []);

  const allCurrentPageSelected = friends.length > 0 && friends.every(f => selected.find(s => s.id === f.id));

  return (
    <Popup
      visible={visible}
      onMaskClick={onClose}
      position="bottom"
      bodyStyle={{ height: "85vh", borderTopLeftRadius: '24px', borderTopRightRadius: '24px' }}
    >
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.title}>选择好友</div>
          <Button size="small" fill="none" onClick={onClose} style={{ color: '#666' }}>
            取消
          </Button>
        </div>

        <div className={styles.searchWrapper}>
          <SearchBar
            placeholder="搜索昵称、微信号、手机号..."
            value={keyword}
            onChange={handleSearch}
            onClear={() => {
              setKeyword("");
              searchFriends("");
            }}
          />
        </div>

        {selected.length > 0 && (
          <div className={styles.selectedBar}>
            <span className={styles.selectedCount}>已选 {selected.length} 人</span>
            <Button size="mini" fill="none" onClick={() => setSelected([])}>
              清空
            </Button>
          </div>
        )}

        <div className={styles.listHeader}>
          <Checkbox
            checked={allCurrentPageSelected}
            onChange={checked => checked ? selectAll() : deselectAll()}
          >
            全选当前页
          </Checkbox>
          <span className={styles.totalCount}>共 {total} 人</span>
        </div>

        <div className={styles.friendList}>
          {loading ? (
            <div className={styles.loadingContainer}>
              <SpinLoading style={{ "--size": "32px" }} />
              <span>搜索中...</span>
            </div>
          ) : friends.length === 0 ? (
            <Empty description={keyword ? "未找到匹配的好友" : "暂无数据"} />
          ) : (
            friends.map(friend => {
              const isSelected = !!selected.find(f => f.id === friend.id);
              return (
                <div
                  key={friend.id}
                  className={`${styles.friendItem} ${isSelected ? styles.selected : ''}`}
                  onClick={() => toggleSelect(friend)}
                >
                  <Checkbox checked={isSelected} />
                  <Avatar src={friend.avatar} className={styles.avatar} />
                  <div className={styles.friendInfo}>
                    <div className={styles.friendName}>{friend.name}</div>
                    {friend.wechatId && (
                      <div className={styles.wechatId}>{friend.wechatId}</div>
                    )}
                    {friend.tags.length > 0 && (
                      <div className={styles.tags}>
                        {friend.tags.map((tag, idx) => (
                          <span key={idx} className={styles.tag}>{tag}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              );
            })
          )}
        </div>

        <div className={styles.footer}>
          <Button
            color="primary"
            block
            disabled={selected.length === 0}
            onClick={handleConfirm}
            className={styles.confirmBtn}
          >
            确认选择 ({selected.length})
          </Button>
        </div>
      </div>
    </Popup>
  );
};

export default FriendSearchModal;
