import React, { useState, useEffect, useRef } from 'react';
import AceEditor from '@easyv/react-ace';
import { Button, Input } from '@easyv/antd';
import { EasySelect, EasyInput, Collapse, Icon } from '@easyv/react-gui';

import styles from './ConditionItem.less';

export default function ConditionItem({
  defaultCollapsed = true,
  value = {},
  onSubmit,
  onCancel,
  onDelete
}: {
  defaultCollapsed?: boolean;
  value?: any;
  onSubmit: (param) => any;
  onCancel: () => any;
  onDelete: (id) => any;
}) {
  const [collapsed, setCollapsed] = useState<boolean>(true);
  const [name, setName] = useState('条件');
  const [type, setType] = useState('field');
  const [field, setField] = useState('');
  const [compare, setCompare] = useState('==');
  const [expected, setExpected] = useState('');
  const [code, setCode] = useState('return data');

  useEffect(() => {
    if (!value.id) {
      setCollapsed(false);
    } else {
      setCollapsed(defaultCollapsed);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (value.id) {
      setName(value.name);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.name]);

  useEffect(() => {
    if (value.id) {
      setType(value.type);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.type]);

  useEffect(() => {
    if (value.id) {
      setField(value.field);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.field]);

  useEffect(() => {
    if (value.id) {
      setCompare(value.compare);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.compare]);

  useEffect(() => {
    if (value.id) {
      setExpected(value.expected);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.expected]);

  useEffect(() => {
    if (value.id) {
      setCode(value.code);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value.code]);

  const onReset = () => {
    setCollapsed(true);
    setType(value.type);
    setName(value.name);
    setField(value.field);
    setCompare(value.compare);
    setExpected(value.expected);
    setCode(value.code);
  };

  const handleCancel = () => {
    onReset();
    onCancel();
  };

  const handleSubmit = async () => {
    const result = await onSubmit({
      ...value,
      name,
      type,
      field,
      compare,
      expected,
      code
    });

    if (result) {
      setCollapsed(true);
    }
  };

  const handleNameComplete = () => {
    // 如果id存在，则表示这是一个已经存在的条件，修改名字需要理解
    if (value.id) {
      onSubmit({
        ...value,
        name,
        type,
        field,
        compare,
        expected,
        code
      });
    }
  };

  const unSave =
    type !== value.type ||
    (type === 'field' ? field !== value.field || compare !== value.compare || expected !== value.expected : code !== value.code);

  return (
    <Collapse
      header={<Header name={name} unSave={unSave} onChange={setName} onDelete={() => onDelete(value.id)} onComplete={handleNameComplete} />}
      collapsed={collapsed}
      onChange={setCollapsed}>
      <div style={{ padding: '12px 16px' }}>
        <div className={styles.container}>
          <label className={styles.label}>类型</label>
          <div className={styles.field}>
            <EasySelect
              value={type}
              options={[
                { name: '字段', value: 'field' },
                { name: '自定义条件', value: 'custom' }
              ]}
              onChange={setType}
            />
          </div>
        </div>

        {type === 'field' && (
          <div className={styles.container}>
            <label className={styles.label}>设置条件</label>
            <div className={styles.field}>
              <EasyInput placeholder="字段名" value={field} onChange={setField} style={{ width: 102, marginRight: 8 }} />
              <EasySelect
                options={[
                  { name: '=', value: '==' },
                  { name: '!=', value: '!=' },
                  { name: '<', value: '<' },
                  { name: '>', value: '>' },
                  { name: '<=', value: '<=' },
                  { name: '>=', value: '>=' },
                  { name: '包含', value: 'include' },
                  { name: '不包含', value: 'exclude' }
                ]}
                value={compare}
                onChange={setCompare}
                style={{ width: 68, marginRight: 8 }}
              />
              <EasyInput placeholder="预期值" value={expected} onChange={setExpected} style={{ width: 102 }} />
            </div>
          </div>
        )}

        {type === 'custom' && (
          <div>
            <div style={{ marginBottom: 6 }}>{'function filter(data){'}</div>
            <AceEditor
              className="dark"
              mode="javascript"
              theme="twilight"
              width="100%"
              height="226px"
              name="responseData"
              tabSize={2}
              value={code}
              showGutter={true}
              editorProps={{ $blockScrolling: true }}
              setOptions={{ wrap: true }}
              onChange={setCode}
            />
            <div style={{ marginTop: 6 }}>{'}'}</div>
          </div>
        )}

        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
          <Button type="primary" ghost style={{ marginRight: 8 }} onClick={handleCancel}>
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            保存
          </Button>
        </div>
      </div>
    </Collapse>
  );
}

const Header = ({ name, unSave, onChange, onDelete, onComplete }) => {
  const [editable, setEditable] = useState(false);

  const inputRef = useRef<Input>(null);

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

  const handleBlur = () => {
    setEditable(false);
    onComplete();
  };

  const handleChange = (e) => {
    onChange(e.target.value);
  };

  return (
    <div className={styles.header} style={{ display: 'flex', flex: 1 }}>
      <span className={styles.name}>
        {editable ? (
          <Input
            ref={inputRef}
            value={name}
            onClick={(e) => e.stopPropagation()}
            onPressEnter={(e: any) => e.target.blur()}
            onBlur={handleBlur}
            onChange={handleChange}
            style={{ background: 'var(--easyv-input-background)', color: 'var(--easyv-text-2)' }}
          />
        ) : (
          <span title={name}>{name}</span>
        )}
      </span>

      <Icon
        type="icon_edit"
        className={styles.edit}
        onClick={(e) => {
          e.stopPropagation();
          setEditable(true);
        }}
      />

      {unSave && (
        <span className={styles.status}>
          <i className={styles.icon} />
          未保存
        </span>
      )}
      <div style={{ flex: 1 }} />
      <Icon
        type="btn_delete"
        className={styles.delete}
        onClick={(e) => {
          e.stopPropagation();
          onDelete();
        }}
      />
    </div>
  );
};
