import React, { forwardRef, memo, useEffect, useRef } from 'react';
import { FixedToolbarButtons, FloatingToolbarButtons } from '@/core/components';
import { PluginOptions, useCreateFlowesPlugin } from '@/core/plugins';
import { cn } from '@udecode/cn';
import { TComboboxItem } from '@udecode/plate-combobox';
import { CommentsProvider, CommentUser } from '@udecode/plate-comments';
import { Plate, PlateProps } from '@udecode/plate-common';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

import { CommentsPopover } from '@/components/plate-ui/comments-popover';
import { CursorOverlay } from '@/components/plate-ui/cursor-overlay';
import { Editor, EditorProps } from '@/components/plate-ui/editor';
import { FixedToolbar } from '@/components/plate-ui/fixed-toolbar';
import { FloatingToolbar } from '@/components/plate-ui/floating-toolbar';
import { MentionCombobox } from '@/components/plate-ui/mention-combobox';
import { TooltipProvider } from '@/components/plate-ui/tooltip';

import '@/styles/globals.css';
import '@/styles/themes.css';

interface CommentsOptions {
  users: Record<number, CommentUser>;
  myUserId: string;
}

export interface FlowesEditorProps
  extends Pick<
      PlateProps,
      | 'value'
      | 'readOnly'
      | 'onChange'
      | 'maxLength'
      | 'initialValue'
      | 'disableCorePlugins'
    >,
    Pick<EditorProps, 'className' | 'style' | 'autoFocus'> {
  mentions?: TComboboxItem[];
  commentsOptions?: CommentsOptions;
  pluginOptions?: PluginOptions;
}

export const FlowesEditor = memo(
  forwardRef((props: FlowesEditorProps, ref: PlateProps['editorRef']) => {
    const {
      value,
      style,
      mentions,
      readOnly,
      onChange,
      maxLength,
      className,
      autoFocus,
      initialValue,
      pluginOptions = {},
      commentsOptions,
      disableCorePlugins,
    } = props;

    const plugins = useCreateFlowesPlugin(pluginOptions);

    const containerRef = useRef(null);

    useEffect(() => {
      const bodyEle = document.querySelectorAll('body')[0];
      bodyEle.classList.add(
        '[&_.slate-selected]:!bg-primary/20',
        '[&_.slate-selection-area]:border',
        '[&_.slate-selection-area]:border-primary',
        '[&_.slate-selection-area]:bg-primary/10'
      );
    }, []);

    return (
      <DndProvider backend={HTML5Backend}>
        <TooltipProvider
          disableHoverableContent
          delayDuration={500}
          skipDelayDuration={0}
        >
          <CommentsProvider
            users={commentsOptions?.users}
            myUserId={commentsOptions?.myUserId}
          >
            <Plate
              value={value}
              editorRef={ref}
              plugins={plugins}
              readOnly={readOnly}
              onChange={onChange}
              maxLength={maxLength}
              initialValue={initialValue}
              disableCorePlugins={disableCorePlugins}
            >
              <div
                ref={containerRef}
                className={cn(
                  'theme-slate',
                  'relative',
                  '[&_.slate-start-area-left]:!w-[64px] [&_.slate-start-area-right]:!w-[64px] [&_.slate-start-area-top]:!h-4'
                )}
              >
                <FixedToolbar>
                  <FixedToolbarButtons />
                </FixedToolbar>

                <Editor
                  className={cn(
                    'px-[96px]',
                    'py-6',
                    'flowes-rich-editor',
                    className
                  )}
                  style={style}
                  autoFocus={autoFocus}
                  focusRing={false}
                  variant="ghost"
                  size="md"
                />

                <FloatingToolbar>
                  <FloatingToolbarButtons />
                </FloatingToolbar>

                <MentionCombobox items={mentions} />

                <CommentsPopover />

                <CursorOverlay containerRef={containerRef} />
              </div>
            </Plate>
          </CommentsProvider>
        </TooltipProvider>
      </DndProvider>
    );
  })
);
