/* eslint-disable @typescript-eslint/no-unused-vars */
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import { CLEAR_EDITOR_COMMAND, LexicalEditor } from 'lexical';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';

import { ActionMenu } from '../../../action-menu';
import { useTr } from '../../i18n';
import { lexicalToCrystallizeRichText } from '../../model/lexical-to-crystallize';
import type { CrystallizeRichTextActionMenuItem } from '../../types/types';

async function copyJson(editor: LexicalEditor) {
  const json = lexicalToCrystallizeRichText({ editor, editorState: editor.getEditorState() });

  try {
    await navigator.clipboard.writeText(JSON.stringify(json, null, 1));
  } catch (error) {
    console.warn('Copy failed', error);
  }
}

type ActionsPluginProps = {
  append?: CrystallizeRichTextActionMenuItem[];
  prepend?: CrystallizeRichTextActionMenuItem[];
  disabled?: boolean;
};

export default function ActionsPlugin({ append, prepend, disabled }: ActionsPluginProps): JSX.Element {
  const [editor] = useLexicalComposerContext();
  const tr = useTr();

  return (
    <ActionMenu>
      {!prepend
        ? null
        : prepend.map(actionItem => (
            <ActionMenu.Item
              key={actionItem.title}
              onSelect={actionItem.action}
              className={actionItem.type === 'danger' ? 'danger' : ''}
              disabled={actionItem.disabled}
            >
              {actionItem.title}
            </ActionMenu.Item>
          ))}
      <ActionMenu.Item onSelect={() => copyJson(editor)}>{tr('actionCopyJSON')}</ActionMenu.Item>
      <ActionMenu.Item
        disabled={disabled}
        className="danger"
        onSelect={() => {
          editor.dispatchCommand(CLEAR_EDITOR_COMMAND, undefined);
          editor.focus();
        }}
      >
        {tr('actionClear')}
      </ActionMenu.Item>
      {!append
        ? null
        : append.map(actionItem => (
            <ActionMenu.Item
              key={actionItem.title}
              onSelect={actionItem.action}
              className={actionItem.type === 'danger' ? 'danger' : ''}
              disabled={actionItem.disabled}
            >
              {actionItem.title}
            </ActionMenu.Item>
          ))}
    </ActionMenu>
  );
}
