// file: SubTimeLineItemModal.tsx
import React, { useEffect } from 'react';
import { Form, Modal, Input, DatePicker, Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import moment from 'moment';

interface ModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  initialValues?: any;
}

const SubTimeLineItemModal: React.FC<ModalProps> = ({ visible, onCancel, onOk, initialValues }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue({
        title: initialValues.title,
        date: initialValues.date ? moment(initialValues.date) : undefined,
        location: initialValues.location,
        description: initialValues.description,
        cover: initialValues.cover,
      });
    }
  }, [initialValues]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const newItem = {
        ...values,
        id: initialValues?.id || Date.now(),
        cover:
          form.getFieldValue('cover') ||
          (initialValues && initialValues.cover),
        date: values.date.format('YYYY-MM-DD'),
      };
      onOk(newItem);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const uploadProps = {
    beforeUpload: () => false,
    onChange: ({ fileList }) => {},
    listType: 'picture' as const,
    maxCount: 1,
  };

  return (
    <Modal
      open={visible}
      title={initialValues ? '编辑时间点' : '添加时间点'}
      onCancel={() => {
        form.resetFields();
        onCancel();
      }}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical" name="timeLineItemForm">
        <Form.Item label="标题" name="title" rules={[{ required: true, message: '请输入标题' }]}>
          <Input placeholder="请输入标题" />
        </Form.Item>

        <Form.Item label="时间" name="date" rules={[{ required: true, message: '请选择时间' }]}>
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item label="地点" name="location">
          <Input placeholder="请输入地点" />
        </Form.Item>

        <Form.Item label="描述" name="description">
          <Input.TextArea rows={4} placeholder="请输入时间点描述" />
        </Form.Item>

        <Form.Item label="封面图片" name="cover">
          <Upload {...uploadProps} maxCount={1}>
            <Button icon={<UploadOutlined />}>上传图片</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default SubTimeLineItemModal;
