import React, { useState, useRef, useEffect, useCallback, useContext, useMemo } from 'react';
import classNames from 'classnames';
import { Tag, Input, Button, Tooltip } from '@easyv/antd';
import AceEditorBox from '../../ScreenConfig/AceEditorBox';
import styles from './ItemContent.less';
import CallBack from '../../ScreenConfig/Callback';
import { QuestionCircleOutlined } from '@easyv/react-icons';
import { DataContext } from '../DataBox/Context/index';
import debounce from 'lodash/debounce';

function ItemContent({
  content,
  collapsed,
  callbackKeys = [],
  showTest,
  onContentChange,
  onCallbackKeysChange,
  onPreviewContent,
  onSubmit,
  onCancel,
  onPreview,
}: {
  content: string;
  collapsed: boolean;
  callbackKeys: any;
  showTest?: boolean;
  onContentChange: (content) => any;
  onCallbackKeysChange: (param) => any;
  onPreviewContent?: (param) => void;
  onSubmit: () => any;
  onCancel: () => any;
  onPreview?: () => any;
}) {
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef<Input>(null);
  const [visible, setVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const { list, editItem, useContainer } = useContext(DataContext);
  const containers = !useContainer ? list : [];

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  const handleCallBack = async (tag) => {
    await setSearchText(tag);
    setVisible(true);
  };

  const closeCallBack = () => {
    setVisible(false);
  };

  const handleClose = (value) => {
    onCallbackKeysChange(callbackKeys.filter((tag) => tag !== value));
  };

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };
  const handleInputConfirm = () => {
    if (inputValue && !callbackKeys.includes(inputValue)) {
      onCallbackKeysChange(callbackKeys.concat(inputValue));
    }

    setInputVisible(false);
    setInputValue('');
  };
  const handleContentChange = useCallback((value) => {
    onContentChange(value);
  }, []);

  const handleDataBox = (value) => {
    onPreviewContent?.(value);
  };
  // TODO回调字段跳转
  return (
    <div className={classNames(styles.container, { collapsed: collapsed })}>
      <div style={{ padding: 16, position: 'relative', width: '100%' }}>
        <div className={styles.header}>
          <label className={styles.label}>回调字段</label>
          <div style={{ flex: 1 }}>
            {callbackKeys.map((tag) => {
              return (
                <Tag
                  key={tag}
                  className={styles.tag}
                  closable={true}
                  onClose={() => handleClose(tag)}>
                  <span
                    style={{ cursor: 'pointer' }}
                    onClick={() => handleCallBack(tag)}
                    id="callback-tag">
                    {tag}
                  </span>
                </Tag>
              );
            })}

            {inputVisible && (
              <Input
                ref={inputRef}
                type="text"
                size="small"
                style={{ width: 78, height: 24, background: 'transparent', color: '#fafafa' }}
                value={inputValue}
                onChange={handleInputChange}
                onBlur={handleInputConfirm}
                onPressEnter={handleInputConfirm}
              />
            )}
            {!inputVisible && (
              <Button
                style={{ verticalAlign: 'top' }}
                onClick={() => setInputVisible(true)}
                type="primary"
                ghost
                size="small">
                + 添加回调
              </Button>
            )}
          </div>
        </div>
        {!useContainer && containers?.length && (!editItem || editItem?.type === 'close') ? (
          <div className={classNames(styles.header, styles.containers)}>
            <label className={styles.label}>
              数据容器
              <Tooltip title="data[]所返回数据依照此处绑定容器顺序">
                <QuestionCircleOutlined className={styles.icon} />
              </Tooltip>
            </label>
            <div className={styles.container}>
              {containers.map((d) => {
                return (
                  <Tag key={d.id} className={styles.tag} onClick={() => handleDataBox(d)}>
                    <Tooltip title={d.name}>
                      <span style={{ cursor: 'pointer' }}>{d.name}</span>
                    </Tooltip>
                  </Tag>
                );
              })}
            </div>
          </div>
        ) : null}

        <div className={styles.codeStart}>
          <span>
            {'function filter('}
            <Tooltip title="数据">
              <span>data</span>
            </Tooltip>
            ,
            <Tooltip title="回调参数集">
              <span>callbackArgs</span>
            </Tooltip>
            {'){'}
          </span>
        </div>
        <div style={{ width: '100%' }}>
          <AceEditorBox
            name="code"
            className="dark"
            mode="javascript"
            theme="twilight"
            width="422px"
            height="200px"
            tabSize={2}
            value={content || ''}
            onChange={handleContentChange}
            enableBasicAutocompletion={true}
            enableLiveAutocompletion={true}
            showGutter={true}
            editorProps={{ $blockScrolling: true }}
            setOptions={{
              wrap: true,
            }}
          />
        </div>

        <div className={styles.codeEnd}>{'}'}</div>
        <div className={styles.operate}>
          <div>
            {showTest && (
              <Button type="primary" ghost onClick={onPreview}>
                测试
              </Button>
            )}
          </div>
          <div>
            <Button type="primary" ghost style={{ marginRight: 8 }} onClick={onCancel}>
              取消
            </Button>
            <Button
              type="primary"
              onClick={debounce(onSubmit, 200, { leading: true, trailing: false })}>
              保存
            </Button>
          </div>
        </div>
      </div>
      <CallBack visible={visible} handleClose={closeCallBack} searchText={searchText} />
    </div>
  );
}

export default ItemContent;
