import React, {
  useImperativeHandle,
  forwardRef,
  useState,
  useEffect,
} from "react";
import {
  Input,
  Button,
  Card,
  Switch,
  Form,
  InputNumber,
  Select,
  Radio,
} from "antd";
import { fetchSocialMediaList, fetchPromotionSiteList } from "../index.api";

interface BasicSettingsProps {
  defaultValues?: {
    name: string;
    startTime: string; // 允许推送的开始时间
    endTime: string; // 允许推送的结束时间
    maxPerDay: number;
    pushOrder: number; // 1: 按最早, 2: 按最新
    isLoop: number; // 0: 否, 1: 是
    pushType: number; // 0: 定时推送, 1: 立即推送
    status: number; // 0: 否, 1: 是
    socialMediaId?: string;
    promotionSiteId?: string;
  };
  onNext: (values: any) => void;
  onSave: (values: any) => void;
  loading?: boolean;
}

export interface BasicSettingsRef {
  validate: () => Promise<boolean>;
  getValues: () => any;
}

const BasicSettings = forwardRef<BasicSettingsRef, BasicSettingsProps>(
  (
    {
      defaultValues = {
        name: "",
        startTime: "06:00", // 允许推送的开始时间
        endTime: "23:59", // 允许推送的结束时间
        maxPerDay: 20,
        pushOrder: 1,
        isLoop: 0, // 0: 否, 1: 是
        pushType: 0, // 0: 定时推送, 1: 立即推送
        status: 0, // 0: 否, 1: 是
        socialMediaId: undefined,
        promotionSiteId: undefined,
      },
    },
    ref,
  ) => {
    const [form] = Form.useForm();
    const [, forceUpdate] = useState({});
    const [socialMediaList, setSocialMediaList] = useState([]);
    const [promotionSiteList, setPromotionSiteList] = useState([]);
    const [loadingSocialMedia, setLoadingSocialMedia] = useState(false);
    const [loadingPromotionSite, setLoadingPromotionSite] = useState(false);

    // 确保组件初始化时能正确显示按钮状态
    useEffect(() => {
      forceUpdate({});
    }, []);

    // 组件挂载时获取社交媒体列表
    useEffect(() => {
      setLoadingSocialMedia(true);
      fetchSocialMediaList()
        .then(res => {
          setSocialMediaList(res);
        })
        .finally(() => {
          setLoadingSocialMedia(false);
        });
    }, []);

    // 监听社交媒体选择变化
    const handleSocialMediaChange = value => {
      form.setFieldsValue({ socialMediaId: value });
      // 清空推广站点选择
      form.setFieldsValue({ promotionSiteId: undefined });
      setPromotionSiteList([]);

      if (value) {
        setLoadingPromotionSite(true);
        fetchPromotionSiteList(value)
          .then(res => {
            setPromotionSiteList(res);
          })
          .finally(() => {
            setLoadingPromotionSite(false);
          });
      }
    };

    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
      validate: async () => {
        try {
          await form.validateFields();
          return true;
        } catch (error) {
          console.log("BasicSettings 表单验证失败:", error);
          return false;
        }
      },
      getValues: () => {
        return form.getFieldsValue();
      },
    }));
    const handlePushOrderChange = (value: number) => {
      form.setFieldsValue({ pushOrder: value });
      forceUpdate({}); // 强制组件重新渲染
    };
    return (
      <div style={{ marginBottom: 24 }}>
        <Card>
          <Form
            form={form}
            layout="vertical"
            initialValues={defaultValues}
            onValuesChange={(changedValues, allValues) => {
              // 当pushOrder值变化时，强制更新组件
              if ("pushOrder" in changedValues) {
                forceUpdate({});
              }
            }}
          >
            {/* 任务名称 */}
            <Form.Item
              label="任务名称"
              name="name"
              rules={[
                { required: true, message: "请输入任务名称" },
                { min: 2, max: 50, message: "任务名称长度在2-50个字符之间" },
              ]}
            >
              <Input placeholder="请输入任务名称" />
            </Form.Item>
            {/* 推送类型 */}
            <Form.Item
              label="推送类型"
              name="pushType"
              rules={[{ required: true, message: "请选择推送类型" }]}
            >
              <Radio.Group>
                <Radio value={0}>定时推送</Radio>
                <Radio value={1}>立即推送</Radio>
              </Radio.Group>
            </Form.Item>
            {/* 允许推送的时间段 - 只在定时推送时显示 */}
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.pushType !== currentValues.pushType
              }
            >
              {({ getFieldValue }) => {
                // 只在pushType为0（定时推送）时显示时间段设置
                return getFieldValue("pushType") === 0 ? (
                  <Form.Item label="允许推送的时间段">
                    <div
                      style={{ display: "flex", gap: 8, alignItems: "center" }}
                    >
                      <Form.Item
                        name="startTime"
                        noStyle
                        rules={[{ required: true, message: "请选择开始时间" }]}
                      >
                        <Input type="time" style={{ width: 120 }} />
                      </Form.Item>
                      <span style={{ color: "#888" }}>至</span>
                      <Form.Item
                        name="endTime"
                        noStyle
                        rules={[{ required: true, message: "请选择结束时间" }]}
                      >
                        <Input type="time" style={{ width: 120 }} />
                      </Form.Item>
                    </div>
                  </Form.Item>
                ) : null;
              }}
            </Form.Item>

            {/* 每日推送 */}
            <Form.Item
              label="每日推送"
              name="maxPerDay"
              rules={[
                { required: true, message: "请输入每日推送数量" },
                {
                  type: "number",
                  min: 1,
                  max: 100,
                  message: "每日推送数量在1-100之间",
                },
              ]}
            >
              <InputNumber
                min={1}
                max={100}
                style={{ width: 120 }}
                addonAfter="条内容"
              />
            </Form.Item>

            {/* 推送顺序 */}
            <Form.Item
              label="推送顺序"
              name="pushOrder"
              rules={[{ required: true, message: "请选择推送顺序" }]}
            >
              <div style={{ display: "flex" }}>
                <Button
                  type={
                    form.getFieldValue("pushOrder") == 1 ? "primary" : "default"
                  }
                  style={{ borderRadius: "6px 0 0 6px" }}
                  onClick={() => handlePushOrderChange(1)}
                >
                  按最早
                </Button>
                <Button
                  type={
                    form.getFieldValue("pushOrder") == 2 ? "primary" : "default"
                  }
                  style={{ borderRadius: "0 6px 6px 0", marginLeft: -1 }}
                  onClick={() => handlePushOrderChange(2)}
                >
                  按最新
                </Button>
              </div>
            </Form.Item>

            {/* 京东联盟 */}
            <Form.Item label="京东联盟" style={{ marginBottom: 16 }}>
              <div style={{ display: "flex", gap: 12, alignItems: "flex-end" }}>
                <Form.Item name="socialMediaId" noStyle>
                  <Select
                    placeholder="请选择社交媒体"
                    style={{ width: 200 }}
                    loading={loadingSocialMedia}
                    onChange={handleSocialMediaChange}
                    options={socialMediaList.map(item => ({
                      label: item.name,
                      value: item.id,
                    }))}
                  />
                </Form.Item>

                <Form.Item name="promotionSiteId" noStyle>
                  <Select
                    placeholder="请选择推广站点"
                    style={{ width: 200 }}
                    loading={loadingPromotionSite}
                    disabled={!form.getFieldValue("socialMediaId")}
                    options={promotionSiteList.map(item => ({
                      label: item.name,
                      value: item.id,
                    }))}
                  />
                </Form.Item>
              </div>
            </Form.Item>

            {/* 是否循环推送 */}
            <Form.Item
              label="是否循环推送"
              name="isLoop"
              valuePropName="checked"
              getValueFromEvent={checked => (checked ? 1 : 0)}
              getValueProps={value => ({ checked: value === 1 })}
            >
              <Switch />
            </Form.Item>

            {/* 是否启用 */}
            <Form.Item
              label="是否启用"
              name="status"
              valuePropName="checked"
              getValueFromEvent={checked => (checked ? 1 : 0)}
              getValueProps={value => ({ checked: value === 1 })}
            >
              <Switch />
            </Form.Item>

            {/* 推送类型提示 */}
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) =>
                prevValues.pushType !== currentValues.pushType
              }
            >
              {({ getFieldValue }) => {
                const pushType = getFieldValue("pushType");
                if (pushType === 1) {
                  return (
                    <div
                      style={{
                        background: "#fffbe6",
                        border: "1px solid #ffe58f",
                        borderRadius: 4,
                        padding: 8,
                        color: "#ad8b00",
                        marginBottom: 16,
                      }}
                    >
                      如果启用立即推送，系统会把内容库里所有的内容按顺序推送到指定的社群
                    </div>
                  );
                }
                return null;
              }}
            </Form.Item>
          </Form>
        </Card>
      </div>
    );
  },
);

BasicSettings.displayName = "BasicSettings";

export default BasicSettings;
