import '@mdxeditor/editor/style.css';

import {
  useEffect,
  useState,
} from 'react';

import {
  CAN_UNDO_COMMAND,
  COMMAND_PRIORITY_CRITICAL,
  UNDO_COMMAND,
} from 'lexical';

import { useAppConfig } from '@/stores/appConfig';
import { mergeRegister } from '@lexical/utils';
import {
  activeEditor$,
  BoldItalicUnderlineToggles,
  ButtonWithTooltip,
  HighlightToggle,
  iconComponentFor$,
  IS_APPLE,
  markdownShortcutPlugin,
  MDXEditor,
  Separator,
  StrikeThroughSupSubToggles,
  toolbarPlugin,
  useTranslation,
} from '@mdxeditor/editor';
import { useCellValues } from '@mdxeditor/gurx';

import DataDescription from './components/DataDescription';
import DataLabel from './components/DataLabel';
import { ItemDataProps } from './types';

function ToolbarUndo() {
    const [iconComponentFor, activeEditor] = useCellValues(iconComponentFor$, activeEditor$);
    const [canUndo, setCanUndo] = useState(false);
    const t = useTranslation();

    useEffect(() => {
        if (!activeEditor) {
            return;
        }
        return mergeRegister(
            activeEditor.registerCommand(
                CAN_UNDO_COMMAND,
                (payload) => {
                    setCanUndo(payload);
                    return false;
                },
                COMMAND_PRIORITY_CRITICAL,
            ),
        );
    }, [activeEditor]);

    return (
        <ButtonWithTooltip
            title={t('toolbar.undo', 'Undo {{shortcut}}', {
                shortcut: IS_APPLE ? '⌘Z' : 'Ctrl+Z',
            })}
            disabled={!canUndo}
            onClick={() => activeEditor?.dispatchCommand(UNDO_COMMAND, undefined)}
        >
            {iconComponentFor('undo')}
        </ButtonWithTooltip>
    );
}

const markdownPlugins = [
    toolbarPlugin({
        toolbarContents: () => (
            <>
                <ToolbarUndo />
                <Separator />
                <BoldItalicUnderlineToggles options={['Bold', 'Italic', 'Underline']} />
                <Separator />
                <HighlightToggle />
                <Separator />
                <StrikeThroughSupSubToggles options={['Strikethrough', 'Sup', 'Sub']} />
            </>
        ),
    }),
    markdownShortcutPlugin(),
];

export const MarkdownData = (props: ItemDataProps) => {



    const [localValue, setLocalValue] = useState(props.getValue());

    useEffect(() => {
        props.setValue(localValue ?? '');
    }, [localValue]);



    const isDarkTheme = useAppConfig().isDarkTheme;


    return (<>

        <DataLabel {...props} />

        <div className='border-[1px] border-gray-200 dark:border-gray-800   rounded-md text-sm'>

            <MDXEditor
                className={isDarkTheme ? "dark-theme dark-editor" : ""}
                markdown={localValue ?? ''}
                onChange={(md) => setLocalValue(md)}
                plugins={markdownPlugins}
            />


        </div>
        <DataDescription {...props} />

    </>
    );



};

