import { Modal, Form, Input, Radio, message } from 'antd';
import { useEffect, useState } from 'react';
import { useProjectStore } from '../stores/useProjectStore';
import { projectApi } from '../api/projectApi';

const { TextArea } = Input;

export const EditProjectDialog = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const {
    currentProject,
    showEditDialog,
    setShowEditDialog,
    updateProject,
  } = useProjectStore();

  // 当对话框打开时，填充表单
  useEffect(() => {
    if (showEditDialog && currentProject) {
      form.setFieldsValue({
        name: currentProject.name,
        researchType: currentProject.researchType,
        background: currentProject.background,
      });
    }
  }, [showEditDialog, currentProject, form]);

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

    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 调用真实API更新项目
      const response = await projectApi.updateProject(currentProject.id, {
        name: values.name,
        background: values.background || '',
        researchType: values.researchType,
      });
      
      if (response.success && response.data) {
        updateProject(currentProject.id, response.data);
        message.success(response.message || '项目更新成功');
        setShowEditDialog(false);
      } else {
        message.error(response.message || '项目更新失败');
      }
    } catch (error) {
      console.error('更新项目失败:', error);
      message.error('项目更新失败');
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <Modal
      title="编辑项目"
      open={showEditDialog}
      onOk={handleOk}
      onCancel={handleCancel}
      width={600}
      okText="保存"
      cancelText="取消"
      confirmLoading={loading}
    >
      <Form
        form={form}
        layout="vertical"
      >
        <Form.Item
          name="name"
          label="项目名称"
          rules={[
            { required: true, message: '请输入项目名称' },
            { max: 100, message: '项目名称不能超过100个字符' },
          ]}
        >
          <Input placeholder="例如：心血管疾病与生活方式关系研究" />
        </Form.Item>

        <Form.Item
          name="researchType"
          label="研究类型"
          rules={[{ required: true, message: '请选择研究类型' }]}
        >
          <Radio.Group>
            <Radio value="observational">观察性研究</Radio>
            <Radio value="interventional">干预性研究</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="background"
          label="项目背景"
          tooltip="可以包括：研究背景、目标人群、研究目的等"
        >
          <TextArea
            rows={6}
            placeholder="请详细描述项目背景信息，AI将基于这些信息提供更精准的建议..."
            maxLength={2000}
            showCount
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

