import React, { useState } from 'react';
import ItemHeader from './ItemHeader';
import ItemContent from './ItemContent';
import message from 'components/message';
import styles from './Item.less';

function FilterAdd({ onSubmit, onRemove }) {
  const [collapsed, setCollapsed] = useState(false);
  const [editable, setEditable] = useState(true);
  const [name, setName] = useState('新建过滤器');
  const [callbackKeys, setCallbackKeys] = useState([]);
  const [content, setContent] = useState('return data;');

  const handleSubmit = async () => {
    if (name && content) {
      onSubmit({
        name: name,
        content: content,
        callbackKeys: callbackKeys,
      });
    } else {
      if (!name) {
        message.error('过滤器名称不能为空');
      } else if (!content) {
        message.error('过滤器内容不能为空');
      }
    }
  };

  return (
    <li className={styles.li}>
      <ItemHeader
        className={styles.header}
        collapsed={collapsed}
        editable={editable}
        name={name}
        unsaved={true}
        onCollapsedChange={setCollapsed}
        onNameChange={setName}
        onEditChange={setEditable}
        onDelete={onRemove}
      />
      <ItemContent
        collapsed={collapsed}
        callbackKeys={callbackKeys}
        content={content}
        onContentChange={setContent}
        onCallbackKeysChange={setCallbackKeys}
        onSubmit={handleSubmit}
        onCancel={onRemove}
      />
    </li>
  );
}

export default FilterAdd;
