import React from 'react';
import dynamic from 'next/dynamic';

import { alpha } from '@mui/material/styles';
import Skeleton from '@mui/material/Skeleton';

import '../libs/highlight';
import { Toolbar } from './toolbar';
import { StyledEditor } from '../libs';
import { IEditorProps, REACT_QUILL_FORMATS } from '../types';

const ReactQuill = dynamic(() => import('react-quill'), {
  ssr: false,
  loading: () => (
    <Skeleton
      sx={{
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        height: 1,
        borderRadius: 1,
        position: 'absolute',
      }}
    />
  ),
});

/**
 * @description {Editor} - Renders the Editor component with the given props.
 * @param {string} id - The id of the editor
 * @param {boolean} error - Whether the editor has an error
 * @param {boolean} simple - Whether the editor is simple
 * @param {string} helperText - The helper text for the editor
 * @param {any} sx - The style object
 * @return {JSX.Element} The rendered Editor component
 */
export const Editor = ({
  id = 'minimal-quill',
  error,
  simple = false,
  helperText,
  sx,
  reactQuillFormats = REACT_QUILL_FORMATS,
  ...other
}: IEditorProps) => {
  const modules = {
    toolbar: {
      container: `#${id}`,
    },
    history: {
      delay: 500,
      maxStack: 100,
      userOnly: true,
    },
    syntax: true,
    clipboard: {
      matchVisual: false,
    },
  };

  return (
    <>
      <StyledEditor
        sx={{
          ...(error && {
            border: (theme) => `solid 1px ${theme.palette.error.main}`,
            '& .ql-editor': {
              bgcolor: (theme) => alpha(theme.palette.error.main, 0.08),
            },
          }),
          ...sx,
        }}
      >
        <Toolbar id={id} simple={simple} />

        <ReactQuill
          modules={modules}
          formats={reactQuillFormats}
          placeholder="Write something awesome..."
          {...other}
        />
      </StyledEditor>

      {helperText && helperText}
    </>
  );
};
