import throttle from 'lodash/throttle';
import * as React from 'react';
import Textarea from '../../components/Textarea';
import SimpleButton from '../../components/SimpleButton';
import { useAdaptable } from '../AdaptableContext';
import clsx from 'clsx';
export const NoteEditor = ({ note, onNoteChange, onClose, editMode, isReadonly }) => {
    const { api } = useAdaptable();
    const showPopupCloseButton = api.optionsApi.getNoteOptions()?.showPopupCloseButton ?? true;
    const textAreaRef = React.useRef(null);
    const [liveValue, setLiveValue] = React.useState(note || '');
    const throttledOnChange = React.useMemo(() => {
        const throttled = throttle((value) => onNoteChange(value), 300);
        return (value) => {
            setLiveValue(value);
            throttled(value);
        };
    }, []);
    React.useEffect(() => {
        if (editMode) {
            textAreaRef.current?.focus();
        }
    }, [editMode]);
    if (note === undefined || note === null) {
        return null;
    }
    return (React.createElement(React.Fragment, null,
        React.createElement(Textarea, { readOnly: isReadonly, ref: textAreaRef, className: clsx('twa:min-w-[180px] twa:min-h-[120px] twa:w-full', {
                'twa:pr-[30px]': showPopupCloseButton,
                'twa:pr-0': !showPopupCloseButton,
            }), value: liveValue, onBlur: () => onClose(), onKeyDown: (event) => {
                if (event.key === 'Escape') {
                    onClose();
                }
            }, onChange: (event) => throttledOnChange(event.target.value) }),
        showPopupCloseButton && (React.createElement(SimpleButton, { variant: "text", style: { position: 'absolute', right: 5, top: 5 }, icon: "close" }))));
};
