import { Form, Input, Modal } from 'antd';
import { useEffect } from 'react';

export interface DeptFormValues {
  name: string;
}

interface DeptModalProps {
  /** 弹窗是否可见 */
  open: boolean;
  /** 弹窗标题 */
  title: string;
  /** 编辑时的初始值，新增时为 undefined */
  initialValues?: DeptFormValues;
  /** 确认回调，返回表单数据 */
  onOk: (values: DeptFormValues) => void;
  /** 取消回调 */
  onCancel: () => void;
}

const DeptModal = ({ open, title, initialValues, onOk, onCancel }: DeptModalProps) => {
  const [form] = Form.useForm<DeptFormValues>();

  // 每次打开时重置并填充表单
  useEffect(() => {
    if (open) {
      form.resetFields();
      if (initialValues) form.setFieldsValue(initialValues);
    }
  }, [open, initialValues, form]);

  const handleOk = async () => {
    const values = await form.validateFields();
    onOk(values);
  };

  return (
    <Modal title={title} open={open} onOk={handleOk} onCancel={onCancel} destroyOnHidden>
      <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
        <Form.Item
          label="部门名称"
          name="name"
          rules={[{ required: true, message: '请输入部门名称' }]}
        >
          <Input placeholder="请输入部门名称" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default DeptModal;
