import React, { Fragment, useEffect, useState } from 'react';
import { View } from 'react-native';
import { Divider } from 'react-native-paper';
import { type Editor } from 'rn-text-editor';
import MenuButton from './EditorMenuButton';
interface EditorMenuProps {
    editor: Editor;
}
const EditorMenu = ({ editor }: EditorMenuProps) => {
    const [_, setForceUpdate] = useState(false);
    useEffect(() => {
        // force the ui to update when the editor updates
        editor.on('update', () => {
            setForceUpdate((prev) => !prev);
        });
    }, []);
    const actions = [
        {
            icon: 'format-bold',
            isActive: editor.isActive('bold'),
            disabled: !editor.commandManager.createCan().toggleBold(),
            onPress() {
                if (editor.commandManager.createCan().toggleBold()) {
                    editor.commandManager
                        .createChain(undefined, true)
                        .toggleBold()
                        .run();
                }
            },
        },
        {
            icon: 'format-italic',
            isActive: editor.isActive('italic'),
            disabled: !editor.commandManager.createCan().toggleItalic(),
            onPress() {
                if (editor.commandManager.createCan().toggleItalic()) {
                    editor.commandManager
                        .createChain(undefined, true)
                        .toggleItalic()
                        .run();
                }
            },
        },
        {
            icon: 'format-color-highlight',
            isActive: editor.isActive('highlight'),
            disabled: !editor.commandManager.createCan().toggleHighlight(),
            onPress() {
                if (editor.commandManager.createCan().toggleHighlight()) {
                    editor.commandManager
                        .createChain(undefined, true)
                        .toggleHighlight()
                        .run();
                }
            },
        },
    ];

    return (
        <View style={{ flexDirection: 'row', justifyContent: "space-between" }}>
            <View style={{ flexDirection: "row", justifyContent: "flex-start", alignItems: "center", flex: 1 }}>
                {actions.map((action, index) => (
                    <Fragment key={index}>
                        <MenuButton
                            key={action.icon}
                            icon={action.icon}
                            isActive={action.isActive}
                            disabled={action.disabled}
                            onPress={action.onPress}
                        />
                        {index < actions.length - 1 && (
                            <Divider />
                        )}
                    </Fragment>
                ))}
            </View>
        </View>
    );
};

export default EditorMenu;