import React from 'react';
import { Drawer, Form, Input, Button, message } from 'antd';
import type { DrawerProps } from 'antd';
import type { WordResult } from '../apis/words';
import { useCreateWord, useUpdateWord } from '../apis/words';

interface WordDrawerProps extends DrawerProps {
  dictID: number;
  initialWord?: WordResult;
  refresh: () => void;
  onClose: () => void;
}

const WordDrawer: React.FC<WordDrawerProps> = ({
  dictID,
  initialWord,
  refresh,
  ...props
}) => {
  const createWord = useCreateWord();
  const updateWord = useUpdateWord();

  return (
    <Drawer
      title={initialWord ? '更新单词' : '创建新单词'}
      destroyOnClose
      {...props}
    >
      <Form
        name="word"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        initialValues={initialWord}
        onFinish={(values: { value: string; meaning: string; extra: string }) =>
          void (async () => {
            try {
              if (initialWord) {
                await updateWord({ ...initialWord, ...values });
                void message.success('更新成功');
              } else {
                await createWord({ ...values, dictID });
                void message.success('创建成功');
              }
              refresh();
              props.onClose();
            } catch (err) {
              if (err instanceof Error) {
                void message.error(err.message);
              }
            }
          })()
        }
      >
        <Form.Item
          label="单词"
          name="value"
          rules={[{ required: true, message: '请输入单词' }]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入单词（如：good）" />
        </Form.Item>
        <Form.Item
          label="词义"
          name="meaning"
          rules={[{ required: true, message: '请输入词义' }]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入词义（如：好的）" />
        </Form.Item>
        <Form.Item label="附加" name="extra">
          <Input placeholder="请输入附加（如：[ɡʊd]）" />
        </Form.Item>
        <Form.Item label=" " colon={false}>
          <Button htmlType="submit" type="primary">
            {initialWord ? '更新' : '创建'}
          </Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default WordDrawer;
