import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useRef } from 'react';
import { EditorState, ContentState, convertFromRaw, convertToRaw, CompositeDecorator, } from 'draft-js';
import { Editor as DraftEditor } from 'react-draft-wysiwyg';
import './TextEditor.scss';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty';
import Typography from '../Typography';
import Tooltip from '../Tooltip';
import Icon from '../Icon';
import useClickOutside from '../../hooks/useClickOutside';
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 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 convertToRaw(ContentState.createFromText(content));
        }
        catch (e) {
            return convertToRaw(ContentState.createFromText(content));
        }
    };
    useEffect(() => {
        let newEditorState;
        try {
            if (!checkEmpty(convertedContent)) {
                const content = parseContent(convertedContent);
                if (content) {
                    newEditorState = EditorState.createWithContent(convertFromRaw(content), linkDecorator);
                }
                else {
                    newEditorState = EditorState.createEmpty(linkDecorator);
                }
            }
            else {
                newEditorState =
                    mode === 'view' || (editableTextEditor && !isEditing)
                        ? EditorState.createWithContent(ContentState.createFromText('---'), linkDecorator)
                        : EditorState.createEmpty(linkDecorator);
            }
        }
        catch (e) {
            console.error('Error creating editor state:', e);
            newEditorState = EditorState.createWithContent(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 = ContentState.createFromText('---');
                newEditorState = EditorState.createWithContent(content, linkDecorator);
            }
            else {
                newEditorState = 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 = 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
                ? EditorState.createWithContent(convertFromRaw(content), linkDecorator)
                : EditorState.createWithContent(ContentState.createFromText('---'), linkDecorator);
            setEditorState(newEditorState);
        }
    };
    useClickOutside(editorRef, handleClickOutside, [buttonsRef]);
    const handleEditorBlur = (event) => {
        if (!editableTextEditor && editorState) {
            const currentContentAsRaw = 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
                ? EditorState.createEmpty(linkDecorator)
                : content
                    ? EditorState.createWithContent(convertFromRaw(content), linkDecorator)
                    : EditorState.createEmpty(linkDecorator);
            setEditorState(newEditorState);
        }
    };
    const handleSubmit = () => {
        if (errorMsg || !editorState) {
            return;
        }
        const currentContentAsRaw = convertToRaw(editorState.getCurrentContent());
        let contentString = JSON.stringify(currentContentAsRaw);
        if (currentContentAsRaw?.blocks[0]?.text === '') {
            contentString = JSON.stringify(convertToRaw(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
            ? EditorState.createWithContent(convertFromRaw(content), linkDecorator)
            : EditorState.createWithContent(ContentState.createFromText('---'), linkDecorator);
        setEditorState(newEditorState);
        setErrorMsg(false);
    };
    const handleFocus = () => {
        setFocusState(true);
        if (onFocus) {
            onFocus();
        }
    };
    const EditorComponent = DraftEditor;
    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 default TextEditor;
//# sourceMappingURL=TextEditor.js.map