import React, { useState, useEffect, useRef } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { Button } from "antd";
import { Toast } from "antd-mobile";
import { createGroupPushTask, fetchGroupPushTaskDetail } from "./index.api";
import Layout from "@/components/Layout/Layout";
import StepIndicator from "@/components/StepIndicator";
import BasicSettings, { BasicSettingsRef } from "./components/BasicSettings";
import GroupSelector, { GroupSelectorRef } from "./components/GroupSelector";
import ContentSelector, {
  ContentSelectorRef,
} from "./components/ContentSelector";
import type { FormData } from "./index.data";
import NavCommon from "@/components/NavCommon";
import { GroupSelectionItem } from "@/components/GroupSelection/data";
import { ContentItem } from "@/components/ContentSelection/data";
const steps = [
  { id: 1, title: "步骤 1", subtitle: "基础设置" },
  { id: 2, title: "步骤 2", subtitle: "选择社群" },
  { id: 3, title: "步骤 3", subtitle: "选择内容库" },
];

const NewGroupPush: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [wechatGroupsOptions, setWechatGroupsOptions] = useState<
    GroupSelectionItem[]
  >([]);
  const [contentGroupsOptions, setContentGroupsOptions] = useState<
    ContentItem[]
  >([]);

  const [formData, setFormData] = useState<FormData>({
    name: "",
    startTime: "06:00", // 允许推送的开始时间
    dailyPushCount: 0, // 每日已推送次数
    endTime: "23:59", // 允许推送的结束时间
    maxPerDay: 20,
    pushOrder: 2, // 2: 按最新
    isLoop: 0, // 0: 否, 1: 是
    pushType: 0, // 0: 定时推送, 1: 立即推送
    status: 0, // 0: 否, 1: 是
    wechatGroups: [],
    contentGroups: [],
  });
  const [isEditMode, setIsEditMode] = useState(false);

  // 创建子组件的ref
  const basicSettingsRef = useRef<BasicSettingsRef>(null);
  const groupSelectorRef = useRef<GroupSelectorRef>(null);
  const contentSelectorRef = useRef<ContentSelectorRef>(null);

  useEffect(() => {
    if (!id) return;
    setIsEditMode(true);
  }, [id]);

  const handleBasicSettingsChange = (values: Partial<FormData>) => {
    setFormData(prev => ({ ...prev, ...values }));
  };

  //群组选择
  const handleGroupsChange = (data: {
    wechatGroups: string[];
    wechatGroupsOptions: GroupSelectionItem[];
  }) => {
    setFormData(prev => ({
      ...prev,
      wechatGroups: data.wechatGroups,
    }));
    setWechatGroupsOptions(data.wechatGroupsOptions);
  };
  //内容库选择
  const handleLibrariesChange = (data: {
    contentGroups: string[];
    contentGroupsOptions: ContentItem[];
  }) => {
    setFormData(prev => ({ ...prev, contentGroups: data.contentGroups }));
    setContentGroupsOptions(data.contentGroupsOptions);
  };

  const handleSave = async () => {
    try {
      // 调用 ContentSelector 的表单校验
      const isValid = (await contentSelectorRef.current?.validate()) || false;
      if (!isValid) return;

      setLoading(true);

      // 获取基础设置中的京东联盟数据
      const basicSettingsValues = basicSettingsRef.current?.getValues() || {};

      // 构建 API 请求数据
      const apiData = {
        name: formData.name,
        startTime: formData.startTime, // 允许推送的开始时间
        endTime: formData.endTime, // 允许推送的结束时间
        maxPerDay: formData.maxPerDay,
        pushOrder: formData.pushOrder,
        isLoop: formData.isLoop, // 0: 否, 1: 是
        pushType: formData.pushType, // 0: 定时推送, 1: 立即推送
        status: formData.status, // 0: 否, 1: 是
        wechatGroups: formData.wechatGroups,
        contentGroups: formData.contentGroups,
        // 京东联盟数据从基础设置中获取
        socialMediaId: basicSettingsValues.socialMediaId,
        promotionSiteId: basicSettingsValues.promotionSiteId,
        pushMode:
          formData.pushType === 1
            ? ("immediate" as const)
            : ("scheduled" as const),
        messageType: "text" as const,
        messageContent: "",
        targetTags: [],
        pushInterval: 60,
      };

      // 打印API请求数据，用于调试
      console.log("发送到API的数据:", apiData);

      // 调用创建或更新 API
      if (id) {
        // 更新逻辑将在这里实现
        Toast.show({ content: "更新成功", position: "top" });
        navigate("/workspace/group-push");
      } else {
        createGroupPushTask(apiData)
          .then(() => {
            Toast.show({ content: "创建成功", position: "top" });
            navigate("/workspace/group-push");
          })
          .catch(() => {
            Toast.show({ content: "创建失败，请稍后重试", position: "top" });
          });
      }
    } catch (error) {
      Toast.show({ content: "保存失败，请稍后重试", position: "top" });
    } finally {
      setLoading(false);
    }
  };

  const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const handleNext = async () => {
    if (currentStep < 3) {
      try {
        let isValid = false;

        switch (currentStep) {
          case 1:
            // 调用 BasicSettings 的表单校验
            isValid = (await basicSettingsRef.current?.validate()) || false;
            if (isValid) {
              const values = basicSettingsRef.current?.getValues();
              if (values) {
                handleBasicSettingsChange(values);
              }
              setCurrentStep(2);
            }
            break;

          case 2:
            // 调用 GroupSelector 的表单校验
            isValid = (await groupSelectorRef.current?.validate()) || false;
            if (isValid) {
              setCurrentStep(3);
            }
            break;

          default:
            setCurrentStep(currentStep + 1);
        }
      } catch (error) {
        console.log("表单验证失败:", error);
      }
    }
  };

  const renderFooter = () => {
    return (
      <div className="footer-btn-group">
        {currentStep > 1 && (
          <Button size="large" onClick={handlePrevious}>
            上一步
          </Button>
        )}
        {currentStep === 3 ? (
          <Button size="large" type="primary" onClick={handleSave}>
            保存
          </Button>
        ) : (
          <Button size="large" type="primary" onClick={handleNext}>
            下一步
          </Button>
        )}
      </div>
    );
  };

  return (
    <Layout
      header={<NavCommon title={isEditMode ? "编辑任务" : "新建任务"} />}
      footer={renderFooter()}
    >
      <div style={{ padding: 12 }}>
        <div style={{ marginBottom: 12 }}>
          <StepIndicator currentStep={currentStep} steps={steps} />
        </div>
        <div>
          {currentStep === 1 && (
            <BasicSettings
              ref={basicSettingsRef}
              defaultValues={{
                name: formData.name,
                startTime: formData.startTime,
                endTime: formData.endTime,
                maxPerDay: formData.maxPerDay,
                pushOrder: formData.pushOrder,
                isLoop: formData.isLoop,
                status: formData.status,
                pushType: formData.pushType,
              }}
              onNext={handleBasicSettingsChange}
              onSave={handleSave}
              loading={loading}
            />
          )}
          {currentStep === 2 && (
            <GroupSelector
              ref={groupSelectorRef}
              selectedGroups={wechatGroupsOptions}
              onPrevious={() => setCurrentStep(1)}
              onNext={handleGroupsChange}
            />
          )}
          {currentStep === 3 && (
            <ContentSelector
              ref={contentSelectorRef}
              selectedOptions={contentGroupsOptions}
              onPrevious={() => setCurrentStep(2)}
              onNext={handleLibrariesChange}
            />
          )}
        </div>
      </div>
    </Layout>
  );
};

export default NewGroupPush;
