import React from 'react';
import { Drawer, Form, Input, Button, message } from 'antd';
import type { DrawerProps } from 'antd';
import { useCreateDict } from '../apis/dicts';

interface DictDrawerProps extends DrawerProps {
  refresh: () => void;
  onClose: () => void;
}

const DictDrawer: React.FC<DictDrawerProps> = ({ refresh, ...props }) => {
  const createDict = useCreateDict();

  return (
    <Drawer title="创建新词库" destroyOnClose {...props}>
      <Form
        name="dict"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        onFinish={(values: {
          name: string;
          value: string;
          meaning: string;
          extra: string;
        }) =>
          void (async () => {
            try {
              await createDict(values);
              void message.success('创建成功');
              refresh();
              props.onClose();
            } catch (err) {
              if (err instanceof Error) {
                void message.error(err.message);
              }
            }
          })()
        }
      >
        <Form.Item
          label="词库名称"
          name="name"
          rules={[{ required: true, message: '请输入词库名称' }]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入词库名称" />
        </Form.Item>
        <Form.Item
          label="单词标题"
          name="value"
          rules={[{ required: true, message: '请输入单词标题' }]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入单词标题（如：英文/日文）" />
        </Form.Item>
        <Form.Item
          label="词义标题"
          name="meaning"
          rules={[{ required: true, message: '请输入词义标题' }]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入词义标题（如：中文）" />
        </Form.Item>
        <Form.Item label="附加标题" name="extra">
          <Input placeholder="请输入附加标题（如：音标/假名）" />
        </Form.Item>
        <Form.Item label=" " colon={false}>
          <Button htmlType="submit" type="primary">
            创建
          </Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default DictDrawer;
