import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect } from 'react';
import Icon from '../Icon/Icon.js';
import Select from '../Select/Select.js';
import { checkEmpty } from '../../utils/checkEmpty/checkEmpty.js';
import classNames from '../../_virtual/index.js';
import Tooltip from '../Tooltip/Tooltip.js';
import Toaster from '../Toast/Toast.js';
import HighlightText from '../HighlightText/HighlightText.js';
import { truncateText, isTextTruncated } from '../../utils/truncateText/truncateText.js';
import Typography from '../Typography/Typography.js';
import useClickOutside from '../../hooks/useClickOutside.js';
import AutoTruncateText from '../AutoTruncateText/AutoTruncateText.js';

const EditLabel = ({ id = '', onConfirm, onCancel, handleCustomError, value = '', label = 'Add Script', optionsList = [], selectedOption = { label: '', value: '' }, withDropdown, inputFieldWidth = 350, selectFieldWidth = 94, textColor = 'var(--nlp-color)', tooltip, required = false, isDisable = { confirm: false, cancel: false, textField: false }, onClick, highlightText = '', isEditable, setIsEditable, cursor = 'pointer', isOnBlurTrue = false, handleOnChange, handleTriggerDoubleClick, truncatedTextCount = 25, truncatedType = 'count', confirmIconTooltip = 'Create', cancelIconTooltip = 'Cancel', inlineValidationError = false, onChangeValidationError = false, isTableTree = false, isAutoTruncate = false, }) => {
    const [isEditing, setIsEditing] = useState(!value);
    const [text, setText] = useState(value ?? '');
    const [clickTimeout, setClickTimeout] = useState(null);
    const [showError, setShowError] = useState('');
    const [toasts, setToasts] = useState({ error: false });
    const [currentSelectedOption, setCurrentSelectedOption] = useState(selectedOption);
    const [shouldShowToast, setShouldShowToast] = useState(false);
    const containerRef = useRef(null);
    const cancelRef = useRef(null);
    const confirmRef = useRef(null);
    const isThrowingError = showError && isEditing ? true : false;
    const inputRef = useRef(null);
    const dropdownRef = useRef(null);
    const isValueFilled = !checkEmpty(text);
    const handleTextFieldChange = (e) => {
        const newValue = e.target.value;
        setText(newValue);
        if (typeof handleOnChange === 'function') {
            handleOnChange(e);
        }
        if (inlineValidationError && onChangeValidationError && isThrowingError) {
            const errorMessage = handleCustomError ? handleCustomError(newValue) : '';
            if (errorMessage) {
                setShowError(errorMessage);
            }
            else {
                setShowError('');
            }
        }
    };
    const onDropdownChangeHandler = (option) => {
        setCurrentSelectedOption(option);
        inputRef.current?.focus();
    };
    const handleDoubleClick = () => {
        if (isDisable.textField)
            return;
        if (clickTimeout) {
            clearTimeout(clickTimeout);
            setClickTimeout(null);
        }
        setIsEditing(true);
        setIsEditable && setIsEditable(id);
        if (handleTriggerDoubleClick) {
            handleTriggerDoubleClick();
        }
    };
    const handleSingleClick = () => {
        if (onClick)
            onClick();
    };
    const handleClick = () => {
        if (clickTimeout) {
            clearTimeout(clickTimeout);
            setClickTimeout(null);
        }
        const timeout = window.setTimeout(() => {
            handleSingleClick();
            setClickTimeout(null);
        }, 1000);
        setClickTimeout(timeout);
    };
    const handleConfirm = () => {
        if (isDisable.confirm)
            return;
        const errorMessage = handleCustomError ? handleCustomError(text) : '';
        if (errorMessage) {
            setShouldShowToast(true);
            handleToastToggle('error');
            setShowError(errorMessage);
            return;
        }
        else {
            setShouldShowToast(false);
            setToasts({ error: false });
            setIsEditing(false);
            setShowError('');
            if (onConfirm)
                onConfirm(text, currentSelectedOption);
            setIsEditable && setIsEditable(null);
        }
    };
    const handleBlur = (event) => {
        if (withDropdown ||
            !isOnBlurTrue ||
            containerRef.current?.contains(event.relatedTarget) ||
            event.relatedTarget === confirmRef.current ||
            event.relatedTarget === cancelRef.current) {
            return;
        }
        setIsEditing(false);
        setText(value);
        setShowError('');
        if (onCancel)
            onCancel();
        setIsEditable && setIsEditable(null);
    };
    const handleOutsideClick = () => {
        if (!isEditing || !containerRef.current)
            return;
        handleCancel();
    };
    useClickOutside(containerRef, handleOutsideClick, [
        confirmRef,
        cancelRef,
        dropdownRef,
    ]);
    const handleCancel = () => {
        if (isDisable.cancel)
            return;
        if (required && !value) {
            const errorMessage = handleCustomError ? handleCustomError(text) : '';
            handleToastToggle('error');
            setShowError(errorMessage);
            setShouldShowToast(true);
            setToasts({ error: true });
            return;
        }
        if (onCancel) {
            onCancel();
        }
        setText(value);
        setCurrentSelectedOption(selectedOption);
        setIsEditing(false);
        setShowError('');
        setIsEditable && setIsEditable(null);
        setShouldShowToast(false);
        setToasts({ error: false });
    };
    const handleKeyDown = (event) => {
        if (event.key === 'Enter' && inputRef.current === document.activeElement) {
            handleConfirm();
            event.stopPropagation();
        }
        else if (event.key === 'Escape') {
            handleCancel();
        }
    };
    const handleToastToggle = (key) => {
        setToasts((prev) => ({ ...prev, [key]: !prev[key] }));
    };
    const getTooltipTitle = () => {
        if (tooltip?.tooltipTitle) {
            return tooltip.tooltipTitle;
        }
        else if (isTextTruncated(text, truncatedTextCount, truncatedType)) {
            return text;
        }
        else {
            return '';
        }
    };
    const getScrollableParent = (element) => {
        if (!element)
            return window;
        let parent = element.parentElement;
        while (parent) {
            const overflowY = window.getComputedStyle(parent).overflowY;
            if (overflowY === 'auto' || overflowY === 'scroll') {
                return parent;
            }
            parent = parent.parentElement;
        }
        return window;
    };
    useEffect(() => {
        if (!containerRef.current || !isEditing)
            return;
        const scrollableParent = getScrollableParent(containerRef.current);
        const handleScroll = () => {
            !isTableTree && handleCancel();
        };
        scrollableParent.addEventListener('scroll', handleScroll, {
            passive: true,
        });
        return () => {
            scrollableParent.removeEventListener('scroll', handleScroll);
        };
    }, [isEditing]);
    useEffect(() => {
        if (value) {
            setText(value);
        }
    }, [value]);
    useEffect(() => {
        if (setIsEditable) {
            if (isEditable) {
                setIsEditing(true);
            }
            else {
                setText(value);
                setIsEditing(false);
            }
        }
    }, [isEditable]);
    return (jsxs("div", { className: 'ff-add-module-container', style: {
            '--add-module-text-color': textColor,
            cursor: (isDisable && cursor) || 'pointer',
        }, ref: containerRef, children: [isEditing && (setIsEditable ? isEditable : true) ? (jsxs("div", { className: "ff-add-module-edit-container", children: [jsxs("fieldset", { className: classNames('ff-add-module-input-with-dropdown', {
                            'ff-add-module-input-with-dropdown--danger': isThrowingError && inlineValidationError,
                        }), children: [jsxs("div", { className: classNames('ff-add-module-input-container', {
                                    'ff-add-module-input-container--float': isValueFilled,
                                }), style: { width: inputFieldWidth }, children: [jsxs("label", { className: "ff-add-module-label-container", htmlFor: "add-module-input", children: [required && jsx("span", { className: "required-asterisk", children: "*" }), jsx("span", { className: classNames('ff-add-module-label', {
                                                    'ff-input-label--no-hover': !!text,
                                                }), children: label })] }), jsx("input", { ref: inputRef, id: "add-module-input", name: "add-module-input", type: "text", className: classNames('ff-add-module-input', {
                                            'ff-add-module-input--border-right': !!withDropdown,
                                        }), onChange: handleTextFieldChange, value: text, required: required, onBlur: handleBlur, disabled: isDisable.textField, onKeyDown: handleKeyDown, autoFocus: true, autoComplete: "off" })] }), withDropdown && (jsx(Select, { dropDownRef: dropdownRef, optionsList: optionsList, selectedOption: currentSelectedOption, showLabel: false, showBorder: false, onChange: onDropdownChangeHandler, optionZIndex: 9999, width: selectFieldWidth, height: 24, className: "ff-add-module-dropdown", selectedOptionColor: "var(--nlp-color)", tooltip: true, showToolTip: true }))] }), jsxs("div", { className: "ff-module-icon-container", children: [jsx(Tooltip, { title: confirmIconTooltip, placement: 'bottom', children: jsx(Icon, { className: "icons", name: "update_icon", onClick: () => !isDisable.confirm && handleConfirm(), color: isDisable.confirm
                                        ? 'var(--default-color)'
                                        : 'var(--label-edit-confirm-icon)', height: 16, width: 16, ref: confirmRef, tabIndex: -1, disabled: isDisable?.confirm }) }), jsx(Tooltip, { title: cancelIconTooltip, placement: 'bottom', children: jsx(Icon, { className: "icons", name: "edit_label_close", onClick: () => !isDisable.cancel && handleCancel(), color: isDisable.cancel
                                        ? 'var(--default-color)'
                                        : 'var(--label-edit-cancel-icon)', height: 12, width: 12, ref: cancelRef, tabIndex: -1, disabled: isDisable?.cancel }) })] })] })) : (jsx(Tooltip, { title: !isAutoTruncate &&
                    isTextTruncated(text, truncatedTextCount, truncatedType)
                    ? getTooltipTitle()
                    : '', placement: tooltip?.tooltipPlacement ?? 'bottom', children: jsx("span", { className: 'ff-add-module-display-text', style: { cursor: (isDisable?.textField && cursor) || 'pointer' }, onDoubleClick: handleDoubleClick, role: "button", onClick: handleClick, children: checkEmpty(highlightText) ? (isAutoTruncate ? (jsxs(AutoTruncateText, { children: [" ", text, " "] })) : (truncateText(text, truncatedTextCount, truncatedType))) : isAutoTruncate ? (jsx(AutoTruncateText, { children: jsx(HighlightText, { text: text, highlight: highlightText }) })) : (jsx(HighlightText, { text: truncateText(text, truncatedTextCount, truncatedType), highlight: truncateText(highlightText, truncatedTextCount, truncatedType) })) }) })), inlineValidationError && showError && isEditing && (jsx(Typography, { as: "p", fontSize: 8, className: "error-text", children: showError })), !inlineValidationError && shouldShowToast && !!showError && (jsx(Toaster, { isOpen: toasts.error, variant: "info", toastTitle: "Info!", toastMessage: showError, onCancelClick: () => handleToastToggle('error'), zIndex: 2000000 }))] }));
};

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