import {useCallback, useRef} from 'react';
import {
  CoreBridge,
  PlaceholderBridge,
  TenTapStartKit,
  useEditorBridge,
} from '@10play/tentap-editor';
import {SetState} from '@interfaces/generic';
import {COLORS} from '@shared/colors';
import {useTheme} from '@shared/theme';

import {editorHtml} from '../editor/editorHtml';
import {MentionBridge} from '../editor/TentapMentionBridge';

interface Props {
  setMessageBody: SetState<string>;
  placeholder: string;
  initialContent?: string;
}

export const useGetEditor = ({
  initialContent,
  setMessageBody,
  placeholder,
}: Props) => {
  const {theme} = useTheme();
  const editorRef = useRef(useEditorBridge());

  const onChange = useCallback(async () => {
    if (editorRef.current) {
      const html = await editorRef.current.getHTML();
      setMessageBody(html === '<p></p>' ? '' : html);
    }
  }, [setMessageBody]);

  editorRef.current = useEditorBridge({
    initialContent,
    autofocus: true,
    dynamicHeight: true,
    onChange,
    customSource: editorHtml,
    theme: {
      webview: {
        backgroundColor: theme.background.elements.default,
      },
    },
    bridgeExtensions: [
      ...TenTapStartKit,
      CoreBridge.configureCSS(`
        body {
          background-color: ${theme.background.elements.default};
          color: ${theme.text.neutral.default};
        }
        .tiptap p.is-editor-empty:first-child::before {
          color: ${theme.text.neutral.lighter};
          content: attr(data-placeholder);
          float: left;
          height: 0;
          pointer-events: none;
          font-size: 16px;
          font-family: 'Roboto', sans-serif;
        }
        p {
          font-size: 16px;
          font-family: 'Roboto', sans-serif;
          color: ${theme.text.neutral.default};
        }
        h1 {
          font-size: 24px;
          font-weight: 700;
          font-family: 'Roboto', sans-serif;
        }
        h2 {
          font-size: 18px;
          font-weight: 700;
          font-family: 'Roboto', sans-serif;
        }
        h3 {
          font-size: 16px;
          font-weight: 400;
          font-family: 'Roboto', sans-serif;
        }
        h4 {
          font-size: 14px;
          font-weight: 400;
          font-family: 'Roboto', sans-serif;
        }
        code {
          background-color: ${COLORS.GRAY_FOURTY_TWO};
          color: ${COLORS.DARK_BLUE_FIVE};
          font-size: 14px;
        }
        a {
          color: ${COLORS.PRIMARY};
          text-decoration-color: ${COLORS.PRIMARY};
        }
      `),
      PlaceholderBridge.configureExtension({placeholder}),
      MentionBridge.configureCSS(`
        .mention {
          color: ${COLORS.PRIMARY};
          text-decoration-line: underline;
          text-decoration-color: ${COLORS.PRIMARY};
        }
      `),
    ],
  });

  return editorRef.current;
};
