import React, { useRef } from 'react';

import { Editor } from '@tinymce/tinymce-react';

// @ts-ignore
import config from '../../../../../../nitrogen.config.js';
import { BuilderModule, PropWysiwyg } from '../../../@types/settings.js';
import wysiwygColors from '../../utils/defaultWysiwygColors.js';
import useKeyPress from '../../utils/useKeyPress.js';

import './CtrlWysiwyg.scss';

type ControlProps = {
  updateProps: (id: string, path: string, value: any) => void;
  deleteProp: (path: string) => void;
  currMod: BuilderModule;
  updatePath: string;
  prop: PropWysiwyg;
  value: any;
  inheritVal?: boolean;
};

let wysiwyg_colors = wysiwygColors;

if (config.wysiwygColors) {
  wysiwyg_colors = config.wysiwygColors;
  wysiwyg_colors = Object.keys(wysiwyg_colors).flatMap((color) => [
    (wysiwyg_colors as { [key: string]: string })[color],
    color,
  ]);
}

const WYSIWYG_COLORS: string[] = wysiwyg_colors as string[];

export default function CtrlWysiwyg({
  currMod,
  updatePath,
  prop,
  value,
  inheritVal,
  deleteProp,
  updateProps,
  saveShortcut,
}: ControlProps & { saveShortcut: () => void }) {
  const editorRef = useRef<any>(null);

  useKeyPress(
    ['s'],
    'ctrl',
    saveShortcut,
    editorRef.current?.editor?.iframeElement?.contentWindow?.document
  );

  return (
    <div
      className={`ctrl-wysiwyg`}
      key={currMod.id + updatePath}
    >
      {prop.clearable !== false && value && !inheritVal && (
        <div
          className='ctrl-wysiwyg__clear-btn'
          onClick={() => deleteProp(updatePath)}
        >
          Clear
        </div>
      )}
      <Editor
        tinymceScriptSrc={'/tinymce/tinymce.min.js'}
        value={inheritVal ? '' : value ?? 'Lorem ipsum dolor sit amet...'}
        onEditorChange={(newValue, editor) =>
          updateProps(currMod.id, updatePath, newValue)
        }
        ref={editorRef}
        init={{
          skin: window.matchMedia('(prefers-color-scheme: dark)').matches
            ? 'oxide-dark'
            : undefined,
          content_css: window.matchMedia('(prefers-color-scheme: dark)').matches
            ? 'dark'
            : undefined,
          placeholder: inheritVal ? value : '',
          plugins: [
            'advlist',
            'autolink',
            'link',
            'lists',
            'charmap',
            'anchor',
            'searchreplace',
            'wordcount',
            'visualblocks',
            'visualchars',
            'code',
            'fullscreen',
            'insertdatetime',
            'table',
            'emoticons',
            'nonbreaking',
          ],
          branding: false,
          promotion: false,
          nonbreaking_wrap: false,
          menubar: 'edit view insert format',
          menu: {
            format: {
              title: 'Format',
              items:
                'bold italic underline strikethrough superscript subscript codeformat | align | forecolor backcolor | language | removeformat',
            },
          },
          toolbar:
            'styles | fullscreen | undo redo | bold italic | bullist numlist | link | alignleft aligncenter alignright alignjustify | outdent indent',
          //TODO: remember to set this back to true. It helps with the grind. - Leo
          paste_as_text: false,
          color_map: WYSIWYG_COLORS,
          ...(prop?.config ?? {}),
        }}
      />
    </div>
  );
}
