import { Button, Col, Divider, Form, Modal, Row, Input } from 'antd';
import { useEffect } from 'react';
import styles from './index.less';
import type { IFormValue, ITypeFormValue } from '@/pages/PromptWord';

interface IEditPromptModalProps {
  open: boolean;
  setOpen: (value: boolean) => void;
  modalType: 'create' | 'edit' | '';
  handleEditPrompt: (value: ITypeFormValue) => void;
  oldRow: IFormValue;
  loading?: boolean;
  handleCreatePrompt: (value: ITypeFormValue) => void;
}

const EditPromptTypeModal = (props: IEditPromptModalProps) => {
  const { open, setOpen, modalType, handleEditPrompt, loading, oldRow, handleCreatePrompt } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    if (modalType === 'create') {
      form.resetFields();
    }

    if (modalType === 'edit') {
      form.setFieldsValue({
        type: oldRow.type,
      });
    }
  }, [open]);

  const handleSavePrompt = async () => {
    const { type } = form.getFieldsValue();
    if (modalType === 'create') {
      await handleCreatePrompt({
        type,
      });
    }

    if (modalType === 'edit') {
      await handleEditPrompt({
        type,
      });
    }

    setOpen(false);
  };

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };

  return (
    <Modal
      open={open}
      centered
      confirmLoading={loading}
      wrapClassName={styles.modal}
      title={modalType === 'create' ? '新增提示类型' : '编辑提示类型'}
      okText="保存"
      onOk={() => {
        setOpen(false);
      }}
      onCancel={() => {
        setOpen(false);
      }}
      width={574}
      footer={null}
    >
      <Form form={form} name="editAndCrateForm" {...layout} onFinish={handleSavePrompt}>
        <Form.Item
          label="提示类型"
          name={'type'}
          rules={[{ required: true, message: '请输入提示类型！' }]}
        >
          <Input />
        </Form.Item>
        <Divider />
        <Row justify={'end'} gutter={8}>
          <Col>
            <Form.Item key={'cancelButton'} noStyle={true}>
              <Button
                key="back"
                onClick={() => {
                  setOpen(false);
                }}
              >
                取消
              </Button>
            </Form.Item>
          </Col>
          <Col>
            <Form.Item key={'saveButton'} noStyle={true}>
              <Button key="submit" type="primary" loading={loading} htmlType="submit">
                保存
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

export default EditPromptTypeModal;
