import CategorySelect from '@/components/CategorySelect';
import { getTopicDetailUsingGET } from '@/services/luigi/topic';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormText } from '@ant-design/pro-form';
import { Button, Col, Form, message, Row } from 'antd';
import React, { useRef } from 'react';

import { saveTopicUsingPOST } from '@/services/luigi/topic';

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 14 },
};

import type { ProFormInstance } from '@ant-design/pro-form';
const TopicForm: React.FC<{
  trigger: JSX.Element;
  formTitle: string;
  topicId?: number;
  refresh?: () => void;
}> = (props) => {
  const formRef = useRef<ProFormInstance<API.PoemBo>>();
  return (
    <DrawerForm<API.TopicDetail>
      title={props.formTitle}
      formRef={formRef}
      layout="horizontal"
      {...formItemLayout}
      trigger={props.trigger}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
      }}
      onVisibleChange={async (visible: boolean) => {
        if (!visible || !props.topicId) {
          return;
        }
        const response = await getTopicDetailUsingGET({ id: props.topicId });
        if (response.data) {
          formRef.current?.setFieldsValue(response.data);
        }
      }}
      onFinish={async (values) => {
        const categoryList: API.Category[] | undefined = values.categoryList;
        if (categoryList) {
          const ids = categoryList.map((x) => x.id);
          const cids = JSON.stringify(ids);
          values.cids = cids;
        }
        const rsp = await saveTopicUsingPOST({ ...values, id: props.topicId });
        if (rsp.code) {
          message.success('提交成功');
          if (props.refresh) {
            props.refresh();
          }
          return true;
        }
        return false;
      }}
    >
      <ProFormText width="md" name="title" label="标题" placeholder="请输入" />
      <Form.List name="categoryList">
        {(fields, { add, remove }, { errors }) => (
          <>
            <Form.Item label="分类" required={true}>
              {fields.map((field) => (
                <Row key={field.key}>
                  <Col span={10}>
                    <Form.Item {...field} key={field.key}>
                      <CategorySelect />
                    </Form.Item>
                  </Col>
                  <Col offset={1}>
                    <MinusCircleOutlined
                      className="dynamic-delete-button"
                      onClick={() => remove(field.name)}
                    />
                  </Col>
                </Row>
              ))}
              <Form.Item>
                <Button
                  type="dashed"
                  onClick={() => add()}
                  style={{ width: '60%' }}
                  icon={<PlusOutlined />}
                >
                  添加分类
                </Button>
                <Form.ErrorList errors={errors} />
              </Form.Item>
            </Form.Item>
          </>
        )}
      </Form.List>
    </DrawerForm>
  );
};

export default TopicForm;
