import React, { useEffect, useState, useRef, useCallback } from "react";
import Layout from "@/components/Layout/Layout";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  MoreOutlined,
} from "@ant-design/icons";
import { Input, Button, Pagination, Dropdown, message } from "antd";
import styles from "./index.module.scss";
import { Empty } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import NavCommon from "@/components/NavCommon";
import { getPackage, deletePackage } from "./api";
import type { Package, PackageList } from "./api";

// 分组图标映射
const getGroupIcon = (type: number, name?: string) => {
  if (type === 0 && name) {
    // type=0时使用分组名称首个字符
    return name.charAt(0).toUpperCase();
  }

  const icons = {
    1: "👥", // 高价值客户池
    2: "📈", // 潜在客户池
    3: "💬", // 高互动客户池
    4: "⭐", // 自定义分组
  };
  return icons[type] || "👥";
};

// 分组颜色映射 - 使用更柔和的现代配色
const getGroupColor = (type: number) => {
  const colors = {
    0: "#F0F2F5", // 浅灰
    1: "#FFF1F0", // 浅红
    2: "#E6F7FF", // 浅蓝
    3: "#F6FFED", // 浅绿
    4: "#F9F0FF", // 浅紫
  };
  return colors[type] || "#E6F7FF";
};

// 分组文字颜色映射
const getGroupTextColor = (type: number) => {
  const colors = {
    0: "#8C8C8C",
    1: "#FF4D4F",
    2: "#1890FF",
    3: "#52C41A",
    4: "#722ED1",
  };
  return colors[type] || "#1890FF";
};

const TrafficPoolList: React.FC = () => {
  const navigate = useNavigate();

  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<Package[]>([]);
  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 handleSearchChange = (value: string) => {
    setSearchInput(value);

    // 清除之前的定时器
    if (debounceTimer.current) {
      clearTimeout(debounceTimer.current);
    }

    // 设置新的定时器，500ms 后执行搜索
    debounceTimer.current = setTimeout(() => {
      setKeyword(value);
    setPage(1);
    }, 500);
  };

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

  const handleRefresh = () => {
    setPage(1);
    fetchData(1);
  };

  const fetchData = useCallback(async (customPage?: number) => {
      setLoading(true);
      try {
        const params = {
        page: customPage || page,
          pageSize,
        keyword,
        };

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

  const handleDelete = async (id: number, name: string) => {
    try {
      // eslint-disable-next-line no-alert
      if (!confirm(`确认删除数据包“${name}”吗？`)) return;
      await deletePackage(id);
      message.success("已删除");
      handleRefresh();
    } catch (e) {
      console.error(e);
      message.error("删除失败");
    }
  };

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return (
    <Layout
      loading={loading}
      header={
        <>
          <NavCommon
            title="流量池"
            right={
              <Button
                type="primary"
                size="small"
                icon={<PlusOutlined />}
                onClick={() => {
                  navigate("/mine/traffic-pool/create");
                }}
              >
                新建分组
              </Button>
            }
          />

          <div className="search-bar">
            <div className="search-input-wrapper">
              <Input
                placeholder="搜索分组"
                value={searchInput}
                onChange={e => handleSearchChange(e.target.value)}
                prefix={<SearchOutlined />}
                allowClear
                size="large"
              />
            </div>
            <Button
              onClick={handleRefresh}
              loading={loading}
              size="large"
              icon={<ReloadOutlined />}
            />
          </div>
        </>
      }
      footer={
        <div className="pagination-container">
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger={false}
            onChange={setPage}
          />
        </div>
      }
    >
      <div className={styles.listWrap}>
        {list.length === 0 && !loading ? (
          <div style={{ paddingTop: 60 }}>
            <Empty description="暂无分组数据" />
          </div>
        ) : (
          <div>
            {list.map(item => (
              <div key={item.id} className={styles.cardCompact}>
                <div className={styles.cardBody}>
                  <div
                    className={styles.menuButton}
                    onClick={e => e.stopPropagation()}
                  >
                    <Dropdown
                      menu={{
                        items: [
                          {
                            key: "preview",
                            label: "预览用户",
                            onClick: () =>
                              navigate(
                                `/mine/traffic-pool/userList/${item.id}`,
                              ),
                          },
                          // 只有非系统分组才显示删除选项
                          ...(item.type !== 1 ? [{
                            key: "delete",
                            danger: true,
                            label: "删除数据包",
                            onClick: () => handleDelete(item.id, item.name),
                          }] : []),
                        ],
                      }}
                      trigger={["click"]}
                    >
                      <MoreOutlined />
                    </Dropdown>
                  </div>

                  <div
                    style={{
                      display: "flex",
                      gap: 16,
                      flex: 1,
                      alignItems: "center",
                    }}
                    onClick={() =>
                      navigate(`/mine/traffic-pool/userList/${item.id}`)
                    }
                  >
                    {/* 左侧图片区域 */}
                    <div
                      className={styles.imageBox}
                      style={{ background: getGroupColor(item.type) }}
                    >
                      {item.pic ? (
                        <img src={item.pic} alt={item.name} />
                      ) : (
                        <span style={{ color: getGroupTextColor(item.type) }}>
                          {getGroupIcon(item.type, item.name)}
                        </span>
                      )}
                    </div>

                    {/* 右侧内容区域 */}
                    <div className={styles.contentArea}>
                      <div className={styles.titleRow}>
                        <div className={styles.title}>{item.name}</div>
                        <div className={styles.countTag}>{item.num}人</div>
                      </div>

                      <div className={styles.metricsRow}>
                        <span className={styles.rfmMain}>RFM {item.RFM}</span>
                        <span className={styles.metricPill}>R:{item.R}</span>
                        <span className={styles.metricPill}>F:{item.F}</span>
                        <span className={styles.metricPill}>M:{item.M}</span>
                      </div>

                      <div className={styles.infoRow}>
                        <span className={styles.typeTag}>
                          {item.type === 0 ? "自定义" : "系统分组"}
                        </span>
                        <span className={styles.time}>
                          {item.createTime?.split(" ")[0] || "-"}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </Layout>
  );
};
//EEws
export default TrafficPoolList;
