import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import type { KnowledgeBase } from '../../api/knowledgeBaseApi';

const { TextArea } = Input;

interface EditKBDialogProps {
  open: boolean;
  knowledgeBase: KnowledgeBase | null;
  onCancel: () => void;
  onUpdate: (id: string, name: string, description?: string) => Promise<void>;
}

const EditKBDialog: React.FC<EditKBDialogProps> = ({
  open,
  knowledgeBase,
  onCancel,
  onUpdate,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 当知识库数据变化时，更新表单
  useEffect(() => {
    if (open && knowledgeBase) {
      form.setFieldsValue({
        name: knowledgeBase.name,
        description: knowledgeBase.description || '',
      });
    }
  }, [open, knowledgeBase, form]);

  const handleOk = async () => {
    if (!knowledgeBase) return;

    try {
      const values = await form.validateFields();
      setLoading(true);
      
      await onUpdate(knowledgeBase.id, values.name, values.description);
      
      message.success('知识库更新成功！');
      onCancel();
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      message.error(error.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title="编辑知识库"
      open={open}
      onOk={handleOk}
      onCancel={handleCancel}
      okText="保存"
      cancelText="取消"
      confirmLoading={loading}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        autoComplete="off"
      >
        <Form.Item
          name="name"
          label="知识库名称"
          rules={[
            { required: true, message: '请输入知识库名称' },
            { max: 50, message: '名称不能超过50个字符' },
          ]}
        >
          <Input 
            placeholder="例如：文献综述资料" 
            maxLength={50}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述（选填）"
          rules={[
            { max: 200, message: '描述不能超过200个字符' },
          ]}
        >
          <TextArea
            placeholder="简要描述该知识库的用途..."
            rows={4}
            maxLength={200}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditKBDialog;


