import React, { useCallback, useEffect, useState, useRef } from "react";
import { useParams, useNavigate } from "react-router-dom";
import Layout from "@/components/Layout/Layout";
import {
  SearchOutlined,
  ReloadOutlined,
  MessageOutlined,
  DollarOutlined,
  AreaChartOutlined,
  UserOutlined,
  EnvironmentOutlined,
  WomanOutlined,
  ManOutlined,
} from "@ant-design/icons";
import { Input, Button, Pagination, Tag } from "antd";
import styles from "./index.module.scss";
import { Empty, Avatar } from "antd-mobile";
import NavCommon from "@/components/NavCommon";
import { fetchTrafficPoolList } from "./api";
import { LIFECYCLE_TEXT } from "../api";
import type { TrafficPoolUser } from "./data";

const defaultAvatar = "https://cdn.jsdelivr.net/gh/maokaka/static/avatar-default.png";

const TrafficPoolUserList: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<TrafficPoolUser[]>([]);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [keyword, setKeyword] = useState("");
  const [searchInput, setSearchInput] = useState("");

  const debounceTimer = useRef<NodeJS.Timeout | null>(null);

  const getList = useCallback(async (customParams?: any) => {
    setLoading(true);
    try {
      const currentPage = customParams?.page || page;
      const params: any = {
        page: currentPage,
        pageSize,
        keyword,
        packageId: id,
        ...customParams,
      };

      const res = await fetchTrafficPoolList(params);
      setList(res.list || []);
      setTotal(res.total || 0);
    } catch (error) {
        console.error("获取列表失败:", error);
    } finally {
      setLoading(false);
    }
  }, [page, pageSize, keyword, id]);

  const handleSearchChange = (value: string) => {
    setSearchInput(value);
    if (debounceTimer.current) clearTimeout(debounceTimer.current);
    debounceTimer.current = setTimeout(() => {
      setKeyword(value);
      setPage(1);
    }, 500);
  };

  useEffect(() => {
    getList({ page: 1 });
  }, [keyword, id]);

  return (
    <Layout
      loading={loading}
      header={
        <>
          <NavCommon title="用户列表" />
          <div className="search-bar">
            <div className="search-input-wrapper">
              <Input
                placeholder="搜索用户姓名/微信号"
                value={searchInput}
                onChange={e => handleSearchChange(e.target.value)}
                prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                allowClear
                size="large"
              />
            </div>
            <Button
              onClick={() => getList()}
              loading={loading}
              icon={<ReloadOutlined />}
            />
          </div>
        </>
      }
      footer={
        <div className="pagination-container">
          <Pagination
            simple
            current={page}
            pageSize={pageSize}
            total={total}
            onChange={newPage => {
              setPage(newPage);
              getList({ page: newPage });
            }}
          />
        </div>
      }
    >
      <div className={styles.listWrap}>
        {list.length === 0 && !loading ? (
          <Empty description="暂无用户数据" />
        ) : (
          <div className={styles.listContainer}>
            {list.map(item => (
              <div
                key={item.id}
                className={styles.cardWrap}
                onClick={() => navigate(`/mine/traffic-pool/detail/${item.wechatId}/${item.id}`)}
                >
                {/* 顶部：头像与基本信息 */}
                <div className={styles.cardHeader}>
                    <Avatar
                      src={item.avatar || defaultAvatar}
                    className={styles.avatar}
                    style={{ "--size": "52px" }}
                    />
                  <div className={styles.mainInfo}>
                    <div className={styles.nicknameRow}>
                      <span className={styles.nickname}>
                        {item.nickname || item.identifier}
                        {item.gender === 1 ? (
                          <ManOutlined style={{ color: "#1677ff", fontSize: "12px", marginLeft: "4px" }} />
                        ) : item.gender === 2 ? (
                          <WomanOutlined style={{ color: "#ff4d4f", fontSize: "12px", marginLeft: "4px" }} />
                        ) : null}
                      </span>
                      <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                        <Tag color="blue" style={{ borderRadius: '4px', fontSize: '10px', border: 'none', margin: 0 }}>
                          {LIFECYCLE_TEXT[item.lifecycle] || "新流量"}
                        </Tag>
                        <Tag color="orange" style={{ borderRadius: '4px', fontSize: '10px', border: 'none', margin: 0 }}>
                          RFM: {item.RFM}
                        </Tag>
                      </div>
                      </div>
                    <div className={styles.wechatId}>
                      <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: '4px' }}>
                        <UserOutlined style={{ fontSize: '12px' }} />
                        {item.wechatId || "未设置微信号"}
                      </div>
                      {item.region && (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '2px', color: '#bfbfbf', fontSize: '11px' }}>
                          <EnvironmentOutlined />
                          {item.region}
                      </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* 中间：互动统计小色块 */}
                <div className={styles.statsRow}>
                  <div className={styles.statItem}>
                    <span className={styles.statLabel}><MessageOutlined /> 消息</span>
                    <span className={styles.statValue}>{item.msgCount || 0}</span>
                  </div>
                  <div className={styles.statItem}>
                    <span className={styles.statLabel}><DollarOutlined /> 成交</span>
                    <span className={styles.statValue}>¥{item.money || 0}</span>
                  </div>
                  <div className={styles.statItem}>
                    <span className={styles.statLabel}><AreaChartOutlined /> 活跃度</span>
                    <span className={styles.statValue}>{item.F || 0}</span>
                  </div>
                </div>

                {/* 底部：用户标签 */}
                <div className={styles.tagsRow}>
                  {item.tags && item.tags.length > 0 ? (
                    <>
                      {item.tags.slice(0, 3).map((tag, idx) => (
                        <span key={idx} className={styles.tagItem}>{tag}</span>
                      ))}
                      {item.tags.length > 3 && <span className={styles.moreTags}>+{item.tags.length - 3}</span>}
                    </>
                  ) : (
                    <span className={styles.noTags}>暂无标签</span>
                  )}
                </div>

                {/* 脚注：来源与时间 */}
                <div className={styles.footerRow}>
                  <span className={styles.source}>{item.fromd}</span>
                  <span>{item.createTime?.split(' ')[0]}</span>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </Layout>
  );
};

export default TrafficPoolUserList;
