import React, { useState } from "react";
import { Button, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import Layout from "@/components/Layout/Layout";
import NavCommon from "@/components/NavCommon";
import BasicInfo from "./components/BasicInfo";
import AudienceFilter from "./components/AudienceFilter";
import UserListPreview from "./components/UserListPreview";
import styles from "./index.module.scss";
import StepIndicator from "@/components/StepIndicator";
import { createTrafficPackage, getUsersByFilter } from "./api";

const CreateTrafficPackage: React.FC = () => {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(1); // 1 基础信息 2 人群筛选 3 用户列表
  const [submitting, setSubmitting] = useState(false); // 添加提交状态
  const [loading, setLoading] = useState(false); // 加载用户列表状态
  const [searchKeyword, setSearchKeyword] = useState(""); // 搜索关键词
  const [currentPage, setCurrentPage] = useState(1); // 当前页
  const [hasMore, setHasMore] = useState(false); // 是否还有更多数据
  const [formData, setFormData] = useState({
    // 基本信息
    name: "",
    description: "",
    remarks: "",
    // 筛选条件
    filterConditions: [],
    // 用户列表
    filteredUsers: [],
    filteredUsersTotal: 0,
  });

  const steps = [
    { id: 1, title: "basic", subtitle: "基本信息" },
    { id: 2, title: "filter", subtitle: "人群筛选" },
    { id: 3, title: "users", subtitle: "预览" },
  ];

  const handleBasicInfoChange = (data: any) => {
    setFormData(prev => ({ ...prev, ...data }));
  };

  const handleFilterChange = (conditions: any[]) => {
    setFormData(prev => ({ ...prev, filterConditions: conditions }));
  };

  const handleGenerateUsers = (users: any[]) => {
    setFormData(prev => ({ ...prev, filteredUsers: users }));
  };


  const handleSubmit = async () => {
    // 防止重复提交
    if (submitting) {
      return;
    }

    if (!formData.name) {
      Toast.show({ content: "请填写流量包名称", icon: "fail" });
      return;
    }

    if (!formData.filterConditions || formData.filterConditions.length === 0) {
      Toast.show({ content: "请设置筛选条件", icon: "fail" });
      return;
    }

    setSubmitting(true);
    try {
      // 构造ruleConfig
      const ruleConfig = {
        logic: "AND",
        conditions: formData.filterConditions,
      };

      // 调用创建接口
      const result = await createTrafficPackage({
        groupName: formData.name,
        description: formData.description || undefined,
        ruleType: 1, // 动态规则
        ruleConfig: ruleConfig,
      });

      Toast.show({ content: "创建成功", icon: "success" });

      // 跳转回列表页
      setTimeout(() => {
        navigate("/mine/traffic-pool");
      }, 1000);
    } catch (error: any) {
      console.error("创建流量包失败:", error);
      Toast.show({ content: error?.message || "创建失败", icon: "fail" });
    } finally {
      setSubmitting(false);
    }
  };

  const canSubmit = formData.name && formData.filterConditions.length > 0;

  // 转换用户数据格式
  const formatUserData = (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}`,
    tags: Array.isArray(user.tags) ? user.tags.map((tag: any) => typeof tag === 'string' ? tag : tag.tagName || '') : [],
    rfmScore: user.rfmScore?.total || 0,
    lastActive: user.lastInteractTime ? `${Math.floor((Date.now() / 1000 - user.lastInteractTime) / 86400)}天前` : "从未",
    consumption: parseFloat(user.totalOrderAmount || "0"),
  });

  // 根据筛选条件获取真实用户数据
  const loadUsersByFilter = async (conditions: any[], keyword: string = "", page: number = 1, append: boolean = false) => {
    if (!conditions || conditions.length === 0) {
      return [];
    }

    setLoading(true);
    try {
      // 构造ruleConfig，如果有关键词搜索，添加额外条件
      let ruleConfig: any = {
        logic: "AND",
        conditions: [...conditions],
      };

      // 如果有搜索关键词，添加搜索条件
      if (keyword) {
        ruleConfig.keyword = keyword;
      }

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

      // 转换为组件需要的格式
      const users = result.list.map(formatUserData);

      // 判断是否还有更多数据
      const totalLoaded = append ? formData.filteredUsers.length + users.length : users.length;
      setHasMore(totalLoaded < result.total);
      setCurrentPage(page);

      if (append) {
        // 追加模式
        setFormData(prev => ({
          ...prev,
          filteredUsers: [...prev.filteredUsers, ...users],
          filteredUsersTotal: result.total,
        }));
      } else {
        // 替换模式
        setFormData(prev => ({
          ...prev,
          filteredUsers: users,
          filteredUsersTotal: result.total,
        }));
      }

      return users;
    } catch (error: any) {
      console.error("获取用户列表失败:", error);
      Toast.show({ content: error?.message || "获取用户列表失败", icon: "fail" });
      return [];
    } finally {
      setLoading(false);
    }
  };

  // 搜索用户
  const handleSearchUsers = async (keyword: string) => {
    setSearchKeyword(keyword);
    setCurrentPage(1);
    await loadUsersByFilter(formData.filterConditions, keyword, 1, false);
  };

  // 加载更多用户
  const handleLoadMoreUsers = async () => {
    if (loading || !hasMore) return;
    await loadUsersByFilter(formData.filterConditions, searchKeyword, currentPage + 1, true);
  };

  const renderFooter = () => {
    return (
      <div className={styles.footer}>
        <div className={styles.buttonGroup}>
          {currentStep > 1 && (
            <Button
              className={styles.prevButton}
              onClick={() => setCurrentStep(s => Math.max(1, s - 1))}
              disabled={submitting}
            >
              上一步
            </Button>
          )}
          {currentStep < 3 ? (
            <Button
              color="primary"
              className={styles.nextButton}
              onClick={async () => {
                if (currentStep === 2) {
                  // 在第二步时加载真实用户列表
                  const users = await loadUsersByFilter(
                    formData.filterConditions,
                  );
                  handleGenerateUsers(users);
                }
                setCurrentStep(s => Math.min(3, s + 1));
              }}
              disabled={submitting || loading}
              loading={loading}
            >
              {currentStep === 2 && loading ? "加载中..." : "下一步"}
            </Button>
          ) : (
            <Button
              color="primary"
              className={styles.submitButton}
              disabled={!canSubmit || submitting}
              loading={submitting}
              onClick={handleSubmit}
            >
              {submitting ? "创建中..." : "创建流量包"}
            </Button>
          )}
        </div>
      </div>
    );
  };

  return (
    <Layout
      header={
        <div className={styles.stepHeader}>
          <NavCommon title="新建流量池" />
          <StepIndicator currentStep={currentStep} steps={steps} />
        </div>
      }
      footer={renderFooter()}
    >
      <div className={styles.content}>
        {currentStep === 1 && (
          <BasicInfo data={formData} onChange={handleBasicInfoChange} />
        )}

        {currentStep === 2 && (
          <AudienceFilter
            conditions={formData.filterConditions}
            onChange={handleFilterChange}
          />
        )}

        {currentStep === 3 && (
          <UserListPreview
            users={formData.filteredUsers}
            total={formData.filteredUsersTotal}
            loading={loading}
            hasMore={hasMore}
            onRemoveUser={userId => {
              setFormData(prev => ({
                ...prev,
                filteredUsers: prev.filteredUsers.filter(
                  (user: any) => user.id !== userId,
                ),
                filteredUsersTotal: prev.filteredUsersTotal - 1,
              }));
            }}
            onSearch={handleSearchUsers}
            onLoadMore={handleLoadMoreUsers}
          />
        )}
      </div>
    </Layout>
  );
};

export default CreateTrafficPackage;
