import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect } from 'react';
import { D as DraftExports } from '../../_virtual/Draft.js';
import { r as reactDraftWysiwygExports } from '../../_virtual/react-draft-wysiwyg.js';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty.js';
import Typography from '../Typography/Typography.js';
import Tooltip from '../Tooltip/Tooltip.js';
import Icon from '../Icon/Icon.js';
import useClickOutside from '../../hooks/useClickOutside.js';

const Link = (props) => {
    const { contentState, entityKey, children } = props;
    const entity = contentState.getEntity(entityKey);
    const { url, target } = entity.getData();
    const handleClick = (e) => {
        e.preventDefault();
        e.stopPropagation();
        if (url) {
            if (target === '_blank' || !target) {
                window.open(url, '_blank', 'noopener,noreferrer');
            }
            else {
                window.open(url, target);
            }
        }
    };
    return (jsx("a", { href: url, target: target || '_blank', rel: "noopener noreferrer", onClick: handleClick, style: {
            color: "var(--ff-step-element-color)",
            textDecoration: 'underline',
            cursor: 'pointer',
        }, children: children }));
};
const createLinkDecorator = () => {
    return new DraftExports.CompositeDecorator([
        {
            strategy: (contentBlock, callback, contentState) => {
                contentBlock.findEntityRanges((character) => {
                    const entityKey = character.getEntity();
                    return entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK';
                }, callback);
            },
            component: Link,
        },
    ]);
};
const TextEditor = ({ convertedContent, setConvertedContent, readOnly, toolbarHidden, toolbarOptions, label, required = false, onBlur, mode, helperText, analyticsClasses = false, error, editableTextEditor = false, onSubmit, onFocus, }) => {
    const [editorState, setEditorState] = useState(null);
    const [focusState, setFocusState] = useState(false);
    const [errorMsg, setErrorMsg] = useState(false);
    const [isEditing, setIsEditing] = useState(false);
    const [initialContent, setInitialContent] = useState(convertedContent);
    const editorRef = useRef(null);
    const buttonsRef = useRef(null);
    const linkDecorator = createLinkDecorator();
    const defaultToolBarOptions = [
        'inline',
        'blockType',
        'fontSize',
        'fontFamily',
        'list',
        'textAlign',
        'colorPicker',
        'link',
        'emoji',
        'image',
        'remove',
        'history',
    ];
    const parseContent = (content) => {
        if (!content)
            return null;
        try {
            const parsed = JSON.parse(content);
            if (parsed && typeof parsed === 'object' && parsed.blocks) {
                return parsed;
            }
            return DraftExports.convertToRaw(DraftExports.ContentState.createFromText(content));
        }
        catch (e) {
            return DraftExports.convertToRaw(DraftExports.ContentState.createFromText(content));
        }
    };
    useEffect(() => {
        let newEditorState;
        try {
            if (!checkEmpty(convertedContent)) {
                const content = parseContent(convertedContent);
                if (content) {
                    newEditorState = DraftExports.EditorState.createWithContent(DraftExports.convertFromRaw(content), linkDecorator);
                }
                else {
                    newEditorState = DraftExports.EditorState.createEmpty(linkDecorator);
                }
            }
            else {
                newEditorState =
                    mode === 'view' || (editableTextEditor && !isEditing)
                        ? DraftExports.EditorState.createWithContent(DraftExports.ContentState.createFromText('---'), linkDecorator)
                        : DraftExports.EditorState.createEmpty(linkDecorator);
            }
        }
        catch (e) {
            console.error('Error creating editor state:', e);
            newEditorState = DraftExports.EditorState.createWithContent(DraftExports.ContentState.createFromText(convertedContent || 'Invalid content'), linkDecorator);
        }
        setEditorState(newEditorState);
        setInitialContent(convertedContent);
    }, [convertedContent, mode, isEditing, editableTextEditor]);
    useEffect(() => {
        if (convertedContent?.length === 0) {
            let newEditorState;
            if (mode === 'view' || (editableTextEditor && !isEditing)) {
                const content = DraftExports.ContentState.createFromText('---');
                newEditorState = DraftExports.EditorState.createWithContent(content, linkDecorator);
            }
            else {
                newEditorState = DraftExports.EditorState.createEmpty(linkDecorator);
            }
            setEditorState(newEditorState);
        }
    }, [convertedContent, mode, isEditing, editableTextEditor]);
    useEffect(() => {
        if (!editorRef.current)
            return;
        const handleLinkClick = (e) => {
            const target = e.target;
            const linkElement = target.closest('a');
            if (linkElement && editorRef.current?.contains(linkElement)) {
                e.preventDefault();
                e.stopPropagation();
                const href = linkElement.getAttribute('href');
                const targetAttr = linkElement.getAttribute('target') || '_blank';
                if (href) {
                    if (targetAttr === '_blank') {
                        window.open(href, '_blank', 'noopener,noreferrer');
                    }
                    else {
                        window.open(href, targetAttr);
                    }
                }
            }
        };
        const editorElement = editorRef.current;
        editorElement.addEventListener('click', handleLinkClick);
        return () => {
            editorElement.removeEventListener('click', handleLinkClick);
        };
    }, []);
    const handleEditorChange = (state) => {
        setEditorState(state);
        const currentContentAsRaw = DraftExports.convertToRaw(state.getCurrentContent());
        if (isEditing && currentContentAsRaw?.blocks[0]?.text === '' && required) {
            setErrorMsg(true);
        }
        else if (currentContentAsRaw?.blocks[0]?.text !== '') {
            setErrorMsg(false);
        }
    };
    const handleClickOutside = () => {
        if (editableTextEditor && isEditing && !errorMsg) {
            setIsEditing(false);
            setConvertedContent(initialContent || '');
            const content = parseContent(initialContent);
            const newEditorState = content
                ? DraftExports.EditorState.createWithContent(DraftExports.convertFromRaw(content), linkDecorator)
                : DraftExports.EditorState.createWithContent(DraftExports.ContentState.createFromText('---'), linkDecorator);
            setEditorState(newEditorState);
        }
    };
    useClickOutside(editorRef, handleClickOutside, [buttonsRef]);
    const handleEditorBlur = (event) => {
        if (!editableTextEditor && editorState) {
            const currentContentAsRaw = DraftExports.convertToRaw(editorState.getCurrentContent());
            setConvertedContent(JSON.stringify(currentContentAsRaw));
            if (currentContentAsRaw?.blocks[0]?.text === '') {
                setErrorMsg(true);
            }
        }
        if (onBlur) {
            onBlur(event);
        }
    };
    const handleDoubleClick = () => {
        if (editableTextEditor && !isEditing) {
            setIsEditing(true);
            setInitialContent(convertedContent);
            const content = parseContent(convertedContent);
            const isDashContent = content?.blocks[0]?.text === '---';
            const newEditorState = isDashContent
                ? DraftExports.EditorState.createEmpty(linkDecorator)
                : content
                    ? DraftExports.EditorState.createWithContent(DraftExports.convertFromRaw(content), linkDecorator)
                    : DraftExports.EditorState.createEmpty(linkDecorator);
            setEditorState(newEditorState);
        }
    };
    const handleSubmit = () => {
        if (errorMsg || !editorState) {
            return;
        }
        const currentContentAsRaw = DraftExports.convertToRaw(editorState.getCurrentContent());
        let contentString = JSON.stringify(currentContentAsRaw);
        if (currentContentAsRaw?.blocks[0]?.text === '') {
            contentString = JSON.stringify(DraftExports.convertToRaw(DraftExports.ContentState.createFromText('---')));
        }
        setConvertedContent(contentString);
        if (onSubmit) {
            onSubmit(contentString);
        }
        setInitialContent(contentString);
        setIsEditing(false);
    };
    const handleCancel = () => {
        setIsEditing(false);
        setConvertedContent(initialContent || '');
        const content = parseContent(initialContent);
        const newEditorState = content
            ? DraftExports.EditorState.createWithContent(DraftExports.convertFromRaw(content), linkDecorator)
            : DraftExports.EditorState.createWithContent(DraftExports.ContentState.createFromText('---'), linkDecorator);
        setEditorState(newEditorState);
        setErrorMsg(false);
    };
    const handleFocus = () => {
        setFocusState(true);
        if (onFocus) {
            onFocus();
        }
    };
    const EditorComponent = reactDraftWysiwygExports.Editor;
    return (jsxs("div", { className: "ff-textEditor-container", children: [jsxs("div", { className: "ff-title-button", children: [jsxs("div", { className: "ff-textEditor-label-asterisk-container", children: [required && (jsx(Typography, { className: "required-asterisk", children: "* " })), label && (jsx(Typography, { lineHeight: "10px", fontWeight: "medium", fontSize: "12px", children: label }))] }), editableTextEditor && isEditing && (jsxs("div", { ref: buttonsRef, className: "ff-textEditor-buttons", children: [jsx(Tooltip, { title: "Update", placement: "bottom", children: jsx(Icon, { name: "update_icon", color: "var(--label-edit-confirm-icon)", height: 20, width: 20, hoverEffect: true, onClick: handleSubmit }) }), jsx(Tooltip, { title: "Cancel", placement: "bottom", children: jsx(Icon, { name: "close", color: "var(--label-edit-cancel-icon)", height: 20, width: 20, onClick: handleCancel, hoverEffect: true }) })] }))] }), jsx("div", { onDoubleClick: handleDoubleClick, children: editorState && (jsx(EditorComponent, { editorState: editorState, onEditorStateChange: handleEditorChange, wrapperClassName: "wrapperClass", editorClassName: `ff-heading-TextEditor-style ${analyticsClasses ? 'fontSm' : 'fontMd'}`, editorStyle: mode !== 'view' && (!editableTextEditor || isEditing)
                        ? !focusState
                            ? {
                                border: '1px solid var(--text-editor-out-focus-border-color) ',
                                borderRadius: '4px',
                                padding: '0px 8px',
                            }
                            : {
                                border: '1px solid var(--text-editor-in-focus-border-color)',
                                borderRadius: '4px',
                                padding: '0px 8px',
                            }
                        : { border: 'none' }, onFocus: handleFocus, onBlur: handleEditorBlur, readOnly: editableTextEditor ? !isEditing : readOnly, toolbarHidden: editableTextEditor ? !isEditing : toolbarHidden, toolbarClassName: "ff-toolbarClass", handlePastedText: () => false, toolbar: {
                        options: Array.isArray(toolbarOptions) && toolbarOptions?.length > 0
                            ? toolbarOptions
                            : defaultToolBarOptions,
                        fontFamily: {
                            options: [
                                'Arial',
                                'Georgia',
                                'Impact',
                                'OpenSans-Regular',
                                'Tahoma',
                                'Times New Roman',
                                'Verdana',
                                'poppins',
                            ],
                        },
                        link: {
                            defaultTargetOption: '_blank',
                            showOpenOptionOnHover: true,
                        },
                    } })) }), (required && errorMsg) || (helperText && error) ? (jsx(Typography, { fontSize: 10, className: 'ff-textEditor-error-msg', as: "span", children: helperText })) : null] }));
};

export { TextEditor as default };
//# sourceMappingURL=TextEditor.js.map
