import { App as AntApp, DatePicker, Form, Input, Modal } from "antd";
import dayjs from "dayjs";
import { useEffect } from "react";

import type { Material } from "../types";

interface AddMaterialModalProps {
  onAdd: (material: Material) => void;
  onOpenChange: (open: boolean) => void;
  open: boolean;
}

interface FormValues {
  associatedDate: dayjs.Dayjs;
  description: string;
}

export function AddMaterialModal({ onAdd, onOpenChange, open }: AddMaterialModalProps) {
  const { message } = AntApp.useApp();
  const [form] = Form.useForm<FormValues>();

  useEffect(() => {
    if (!open) return;
    form.resetFields();
  }, [form, open]);

  const handleFinish = (values: FormValues) => {
    const material: Material = {
      associatedDate: values.associatedDate.format("YYYY-MM-DD"),
      createdAt: new Date().toISOString(),
      description: values.description,
      id: crypto.randomUUID(),
    };
    onAdd(material);
    message.success("素材已添加");
    onOpenChange(false);
  };

  return (
    <Modal
      destroyOnHidden
      okText="确定"
      onCancel={() => onOpenChange(false)}
      onOk={() => void form.submit()}
      open={open}
      title="新增素材"
    >
      <Form
        form={form}
        initialValues={{ associatedDate: dayjs() }}
        layout="vertical"
        onFinish={(values) => void handleFinish(values)}
      >
        <Form.Item
          label="描述"
          name="description"
          rules={[{ message: "请输入描述", required: true, whitespace: true }]}
        >
          <Input.TextArea maxLength={500} placeholder="请输入素材描述" />
        </Form.Item>
        <Form.Item label="关联时间" name="associatedDate" rules={[{ message: "请选择关联时间", required: true }]}>
          <DatePicker className="app-inbox-datepicker" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
