import React, { useState, useEffect, useRef } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import GenericFields from 'components/formHelpers/GenericFields';
import ModuleButton from 'components/items/ModuleButton';
import styleIdentifiers from './jsonField.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type JsonFieldProps = StateProps & DispatchProps & OwnProps;

const JsonField = (props: JsonFieldProps) => {
  const { input } = props;

  const [jsonString, setJsonString] = useState('');

  const refInput = useRef();

  function safelyParseJSON(json) {
    // This function cannot be optimised, it's best to
    // keep it small!
    let parsed;

    try {
      parsed = JSON.parse(json);
    } catch (e) {
      return `Error: ${e.message}`;
    }

    return parsed; // Could be undefined!
  }

  function handleUserKeyPress() {
    let value = input.value;
    let position;

    if (value.length !== 0) {
      if (value[0] !== '{') value = `{${value}`;
      if (value[value.length - 1] !== '}') {
        value = `${value}}`;
        position = value.length - 1;
      }
    }

    value = value.replace(/'/g, '"');

    input.onChange(value);

    if (position) refInput.current.setSelectionRange(position, position);
  }

  useEffect(() => {
    window.addEventListener('keyup', handleUserKeyPress);

    return () => {
      window.removeEventListener('keyup', handleUserKeyPress);
    };
  });

  useEffect(() => {
    input.onChange(JSON.stringify(input.value));
  }, []);

  return (
    <div className={styles('json-field')}>
      <div className={styles('content-wrapper')}>
        <textarea rows={10} ref={refInput} {...input} placeholder="{}" />
      </div>
      <div className={styles('json-value')}>
        {input.value && (
          <>
            {typeof safelyParseJSON(input.value) === 'string' ? (
              <div className={styles('json-error')}>{safelyParseJSON(input.value)}</div>
            ) : (
              <div className={styles('json-res')}>
                {JSON.stringify(JSON.parse(input.value), null, '\t')}
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default JsonField;
