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

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

import Editor from 'react-simple-code-editor';

import classNames from 'classnames/bind';
import { highlight, languages } from 'prismjs/components/prism-core';

// required
import 'prismjs/components/prism-clike';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-jsx';
import 'prismjs/components/prism-json';

import '!style-loader!css-loader!prismjs/themes/prism.css';

import FormElement from 'components/structure/FormElement';
import FieldWrapper from 'components/structure/FieldWrapper';

import TextItem from 'components/items/TextItem';
import app from 'store/app';
import styleIdentifiers from './codeEditorInput.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  language: 'jsx' | 'javascript' | 'markup' | 'json';
}

export type CodeEditorInputProps = StateProps & DispatchProps & OwnProps;

const CodeEditorInput = (props: CodeEditorInputProps) => {
  // mapStateToProps

  const {
    input,
    className,
    valueClassName,
    contentWrapperClassName,
    padding,
    fontSize,
    fontFamily,
    language,
    tabSize,
    iframe,
  } = props;

  const dispatch = useDispatch();

  const dialogShow = data => dispatch(app.actions.dialog.show.action(data));

  const preview = () => {
    dialogShow({
      id: 'code-preview',
      children: (
        <div className={styles('preview-modal')}>
          {iframe && (
            <iframe
              className={styles('preview-iframe')}
              title="code-preview"
              src={`data:text/html;charset=utf-8,${encodeURI(input.value)}`}
            />
          )}

          {!iframe && <TextItem className={styles('preview-code')} item={input.value} isHtml />}
        </div>
      ),
    });
  };

  return (
    <FormElement {...props} className={styles('code-editor-input', className)}>
      <FieldWrapper
        {...props}
        contentWrapperClassName={styles('content', contentWrapperClassName)}
        valueClassName={styles('code-value', valueClassName)}
      >
        <div className={styles('preview')} onClick={preview}>
          Preview
        </div>
        <Editor
          value={input.value}
          onValueChange={code => input.onChange(code)}
          highlight={code => highlight(code, languages[language || 'jsx'])}
          padding={padding || 12}
          tabSize={tabSize || 4}
          style={{
            fontFamily,
            fontSize: fontSize || 13,
            lineHeight: 1.45,
          }}
        />
      </FieldWrapper>
    </FormElement>
  );
};

export default CodeEditorInput;
