import { Form, Input, Modal, Select } from 'antd';
import { useEffect, useState } from 'react';
import { getGroupListByYagId } from '@/services/ai/sample';

interface TagsModalProps {
  visible: boolean;
  type: 'group' | 'tag';
  modalType?: 'add' | 'edit' | 'delete';
  onCancel: () => void;
  groups: { id?: number; groupName?: string }[];
  value: {
    id?: number;
    tagName?: string;
    groupIds?: number[];
    groupName?: string;
  };
  onConfirm: (
    values: { groupIds?: number[]; name: string },
    type: 'group' | 'tag',
  ) => void;
}
const TagsModal = (props: TagsModalProps) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const { value, visible, type, modalType, groups, onCancel, onConfirm } =
    props;

  const onGroupListByYagId = async (id: number) => {
    const groupItem: { id?: number; groupName?: string }[] =
      await getGroupListByYagId(id);
    form.setFieldsValue({
      groupIds: groupItem.map((item) => item.id),
    });
  };
  useEffect(() => {
    form.setFieldsValue(value);
    console.log('value', value);
    if (visible && type === 'tag' && value.id) {
      onGroupListByYagId(value.id);
    }
    return () => {
      form.resetFields();
      setLoading(false);
    };
  }, [visible, value]);
  const handleOk = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      await onConfirm(values, type);
    } finally {
      setLoading(false);
    }
  };
  return (
    <Modal
      title={`${modalType === 'add' ? '添加' : '编辑'}${
        type === 'group' ? '分组' : '标签'
      }`}
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      okText="确定"
      confirmLoading={loading}
      cancelText="取消"
      destroyOnHidden
      width={400}
    >
      <Form
        name="form"
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        style={{ maxWidth: 600, marginTop: 30 }}
      >
        {type === 'tag' && (
          <Form.Item
            label="分组"
            name="groupIds"
            rules={[{ required: true, message: '请选择分组' }]}
          >
            <Select
              mode="multiple"
              style={{ width: '100%', marginBottom: 10 }}
              options={groups}
              placeholder="请选择分组"
              fieldNames={{ label: 'groupName', value: 'id' }}
            ></Select>
          </Form.Item>
        )}
        {type === 'tag' ? (
          <Form.Item
            label="标签"
            name="tagName"
            rules={[{ required: true, message: '请输入标签' }]}
          >
            <Input placeholder="请输入标签" />
          </Form.Item>
        ) : (
          <Form.Item
            label="分组"
            name="groupName"
            rules={[{ required: true, message: '请输入分组' }]}
          >
            <Input placeholder="请输入分组" />
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
};

export default TagsModal;
