import React, { useImperativeHandle, forwardRef } from "react";
import { Form, Card } from "antd";
import GroupSelection from "@/components/GroupSelection";
import { GroupSelectionItem } from "@/components/GroupSelection/data";

interface GroupSelectorProps {
  selectedGroups: GroupSelectionItem[];
  onPrevious: () => void;
  onNext: (data: {
    wechatGroups: string[];
    wechatGroupsOptions: GroupSelectionItem[];
  }) => void;
}

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

const GroupSelector = forwardRef<GroupSelectorRef, GroupSelectorProps>(
  ({ selectedGroups, onNext }, ref) => {
    const [form] = Form.useForm();

    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
      validate: async () => {
        try {
          form.setFieldsValue({
            wechatGroups: selectedGroups.map(item => item.id),
          });
          await form.validateFields();
          return true;
        } catch (error) {
          console.log("GroupSelector 表单验证失败:", error);
          return false;
        }
      },
      getValues: () => {
        return form.getFieldsValue();
      },
    }));

    // 群组选择
    const handleGroupSelect = (wechatGroupsOptions: GroupSelectionItem[]) => {
      const wechatGroups = wechatGroupsOptions.map(item => item.id);
      form.setFieldValue("wechatGroups", wechatGroups);
      onNext({ wechatGroups, wechatGroupsOptions });
    };

    return (
      <Card>
        <Form
          form={form}
          layout="vertical"
          initialValues={{ groups: selectedGroups }}
        >
          <div style={{ marginBottom: 20 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
              选择推送群组
            </h2>
            <p style={{ margin: "8px 0 0 0", color: "#666", fontSize: 14 }}>
              请选择要推送消息的微信群组
            </p>
          </div>

          <Form.Item
            name="wechatGroups"
            rules={[
              {
                required: true,
                type: "array",
                min: 1,
                message: "请选择至少一个群组",
              },
              { type: "array", max: 50, message: "最多只能选择50个群组" },
            ]}
          >
            <GroupSelection
              selectedOptions={selectedGroups}
              onSelect={handleGroupSelect}
              placeholder="选择要推送的群组"
              readonly={false}
              showSelectedList={true}
              selectedListMaxHeight={300}
            />
          </Form.Item>
        </Form>
      </Card>
    );
  },
);

GroupSelector.displayName = "GroupSelector";

export default GroupSelector;
