import React, { useState, useRef, useEffect } from "react";
import { Avatar, Button, Checkbox, Empty, SearchBar, InfiniteScroll, SpinLoading } from "antd-mobile";
import { CloseCircleOutline } from "antd-mobile-icons";
import styles from "./UserListPreview.module.scss";

interface User {
  id: string;
  name: string;
  avatar: string;
  tags: string[];
  rfmScore: number;
  lastActive: string;
  consumption: number;
}

interface UserListPreviewProps {
  users: User[];
  total?: number;
  loading?: boolean;
  hasMore?: boolean;
  onRemoveUser: (userId: string) => void;
  onSearch?: (keyword: string) => void;
  onLoadMore?: () => Promise<void>;
}

const UserListPreview: React.FC<UserListPreviewProps> = ({
  users,
  total = 0,
  loading = false,
  hasMore = false,
  onRemoveUser,
  onSearch,
  onLoadMore,
}) => {
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [searchKeyword, setSearchKeyword] = useState("");
  const debounceTimer = useRef<NodeJS.Timeout | null>(null);

  // 搜索防抖
  const handleSearchChange = (value: string) => {
    setSearchKeyword(value);

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

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

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

  const getRfmBadge = (score: number) => {
    if (score >= 12) return { text: "CORE", color: "#ff3b30", bg: "#fff2f1" };
    if (score >= 8) return { text: "HIGH", color: "#ff9500", bg: "#fff9f2" };
    return { text: "USER", color: "#8e8e93", bg: "#f2f2f7" };
  };

  // 本地筛选（如果没有提供onSearch回调）
  const filteredUsers = onSearch
    ? users
    : users.filter(user => {
        if (!searchKeyword) return true;
        const keyword = searchKeyword.toLowerCase();
        return (
          user.name?.toLowerCase().includes(keyword) ||
          user.tags?.some(tag => tag.toLowerCase().includes(keyword))
        );
      });

  const displayTotal = total || filteredUsers.length;

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.title}>符合条件的用户</div>
        <div className={styles.userCount}>{displayTotal}人</div>
      </div>

      {/* 搜索框 */}
      <div className={styles.searchWrapper}>
        <SearchBar
          placeholder="搜索昵称、微信号、标签..."
          value={searchKeyword}
          onChange={handleSearchChange}
          onClear={() => {
            setSearchKeyword("");
            onSearch?.("");
          }}
        />
      </div>

      {loading && users.length === 0 ? (
        <div className={styles.loadingContainer}>
          <SpinLoading style={{ "--size": "32px" }} />
          <span>加载中...</span>
        </div>
      ) : filteredUsers.length === 0 ? (
        <div style={{ paddingTop: 40 }}>
          <Empty description={searchKeyword ? "未找到匹配用户" : "暂无用户数据"} />
        </div>
      ) : (
        <>
          <div className={styles.batchBar}>
            <Checkbox
              checked={selectedUsers.length === filteredUsers.length && filteredUsers.length > 0}
              onChange={checked => setSelectedUsers(checked ? filteredUsers.map(u => u.id) : [])}
              style={{ '--font-size': '14px' }}
            >
              全选
            </Checkbox>
            {selectedUsers.length > 0 && (
              <Button size="mini" color="danger" fill="none" onClick={() => {
                selectedUsers.forEach(onRemoveUser);
                setSelectedUsers([]);
              }}>
                批量删除 ({selectedUsers.length})
              </Button>
            )}
          </div>

          <div className={styles.userList}>
            {filteredUsers.map(user => {
              const badge = getRfmBadge(user.rfmScore);
              return (
                <div key={user.id} className={styles.userItem}>
                  <Checkbox
                    checked={selectedUsers.includes(user.id)}
                    onChange={checked => setSelectedUsers(prev => checked ? [...prev, user.id] : prev.filter(id => id !== user.id))}
                  />
                  <Avatar src={user.avatar} className={styles.avatar} />
                  <div className={styles.userInfo}>
                    <div className={styles.nameRow}>
                      <span className={styles.userName}>{user.name}</span>
                      <span className={styles.badge} style={{ color: badge.color, background: badge.bg }}>
                        {badge.text}
                      </span>
                    </div>
                    <div className={styles.metaRow}>
                      消费 ¥{user.consumption} · 活跃 {user.lastActive}
                    </div>
                    {user.tags && user.tags.length > 0 && (
                      <div className={styles.tagsRow}>
                        {user.tags.slice(0, 3).map((tag, idx) => (
                          <span key={idx} className={styles.tagItem}>{tag}</span>
                        ))}
                        {user.tags.length > 3 && (
                          <span className={styles.tagMore}>+{user.tags.length - 3}</span>
                        )}
                      </div>
                    )}
                  </div>
                  <Button
                    fill="none"
                    className={styles.removeBtn}
                    onClick={() => onRemoveUser(user.id)}
                  >
                    <CloseCircleOutline />
                  </Button>
                </div>
              );
            })}
          </div>

          {/* 无限滚动加载更多 */}
          {onLoadMore && (
            <InfiniteScroll loadMore={onLoadMore} hasMore={hasMore}>
              {hasMore ? (
                <div className={styles.loadingMore}>
                  <SpinLoading style={{ "--size": "24px" }} />
                  <span>加载中...</span>
                </div>
              ) : (
                <span>没有更多了</span>
              )}
            </InfiniteScroll>
          )}
        </>
      )}
    </div>
  );
};

export default UserListPreview;
