import { jsxs, jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect } from 'react';
import Typography from '../Typography/Typography.js';
import HighlightText from '../HighlightText/HighlightText.js';
import Icon from '../Icon/Icon.js';
import Tooltip from '../Tooltip/Tooltip.js';
import Input from '../Input/Input.js';
import Select from '../Select/Select.js';
import useEscapeKey from '../../hooks/keyboardevents/useEscKeyEvent.js';
import { useKeyboardActions } from '../../utils/keyBoardActionUtil/UseKeyboardActions.js';
import { WHITESPACE_REGEX } from '../../validations/regex.js';

const getErrorMessage = (inputValue, text, customError, customErrorCondition) => {
    if (inputValue === text) {
        return 'No changes were made.';
    }
    else if (!inputValue) {
        return 'Text is required';
    }
    else if (inputValue.length < 3) {
        return 'Please enter at least 3 characters.';
    }
    else ;
    return '';
};
const LabelEditTextField = ({ label, placeholder, text, showText = true, highlightText, customError, confirmIcon, customErrorCondition, cancelIcon, variant = 'textField', onInputChange, dropdownData = [], 
// width,
className, height, isOpen = false, confirmAction, onClick, tooltip, onDoubleClick, disableEditing = false, }) => {
    const [isEditing, setIsEditing] = useState(isOpen ?? false);
    const [inputValue, setInputValue] = useState(text ?? '');
    const [dropdownValue, setDropdownValue] = useState(dropdownData[0]?.value ?? '');
    const [showError, setShowError] = useState('');
    const [disabled, isDisabled] = useState(true);
    const [isTextFieldModified, setIsTextFieldModified] = useState(false);
    const isThrowingError = showError && isEditing ? true : false;
    const containerRef = useRef(null);
    const cancelRef = useRef(null);
    const [clickTimeout, setClickTimeout] = useState(null);
    const handleEsc = useEscapeKey('Escape');
    useEffect(() => {
        return () => {
            if (clickTimeout) {
                clearTimeout(clickTimeout);
            }
        };
    }, [clickTimeout]);
    const handleDoubleClick = () => {
        if (disableEditing)
            return;
        if (clickTimeout) {
            clearTimeout(clickTimeout);
            setClickTimeout(null);
        }
        onDoubleClick && onDoubleClick();
        setIsEditing(true);
        setShowError('');
    };
    const handleSingleClick = () => {
        if (onClick)
            onClick();
    };
    const handleClick = () => {
        if (disableEditing)
            return;
        if (clickTimeout) {
            clearTimeout(clickTimeout);
            setClickTimeout(null);
        }
        const timeout = window.setTimeout(() => {
            handleSingleClick();
            setClickTimeout(null);
        }, 1000);
        setClickTimeout(timeout);
    };
    const handleConfirm = () => {
        let errorMessage = '';
        if (inputValue.length === 0 || inputValue.trim().length === 0) {
            errorMessage = 'Please type any text.';
        }
        else if (inputValue.length < 3) {
            errorMessage = 'Please enter at least 3 characters.';
        }
        else if (customErrorCondition) {
            errorMessage = customError ?? 'Invalid input.';
        }
        if (errorMessage) {
            setShowError(errorMessage);
        }
        else {
            setIsEditing(false);
            setShowError('');
            if (confirmAction)
                confirmAction(inputValue, dropdownValue);
        }
        confirmIcon?.onClick?.();
    };
    const handleCancel = () => {
        setInputValue(text ?? '');
        setDropdownValue(dropdownData[0]?.value ?? '');
        setIsEditing(false);
        setShowError('');
        setIsTextFieldModified(false);
        cancelIcon?.onClick?.();
    };
    const handleTextFieldChange = (e) => {
        const newValue = e.target.value;
        setInputValue(newValue);
        isDisabled(false);
        if (newValue.length === 0 || newValue.trim().length === 0) {
            setShowError('Input is required');
        }
        else if (newValue.length < 3) {
            setShowError('Input cannot be less than 3 characters');
        }
        else if (newValue.length > 250) {
            setShowError('Input cannot be more than 250 characters');
        }
        else if (WHITESPACE_REGEX.test(newValue)) {
            setShowError('Space is not allowed at starting and at the end');
        }
        else if (customErrorCondition) {
            setShowError(customError ?? 'Invalid input.');
        }
        else {
            setShowError('');
        }
        setIsTextFieldModified(newValue !== text);
        if (onInputChange) {
            onInputChange(newValue);
        }
    };
    const handleBlur = (e) => {
        if (containerRef.current &&
            !containerRef.current.contains(e.target) &&
            cancelRef.current !== e.target) {
            const errorMessage = getErrorMessage(inputValue, text ?? '');
            if (errorMessage && isEditing) {
                setShowError(errorMessage);
            }
            else {
                setIsEditing(false);
                setShowError('');
            }
        }
    };
    useEffect(() => {
        document.addEventListener('click', handleBlur);
        return () => {
            document.removeEventListener('click', handleBlur);
        };
    }, [inputValue]);
    handleEsc(handleCancel);
    function handleKeyBoard(key) {
        {
            handleConfirm();
        }
    }
    useKeyboardActions([{ key: 'Enter', action: () => handleKeyBoard() }], containerRef);
    return (jsxs("div", { className: "ff-label-edit-text-field", ref: containerRef, children: [isEditing ? (jsxs("div", { className: "ff-label-text-field", children: [variant === 'textFieldWithDropdown' ? (jsxs("div", { className: `ff-label-text-field-with-dropdown ${isEditing ? 'open' : ''}`, style: { height }, children: [jsx(Input, { name: "input", type: "text", label: label ? label : '', disabled: false, error: isThrowingError, placeholder: placeholder ? placeholder : '', value: inputValue, onChange: handleTextFieldChange, className: `${className} 
                
               ${isTextFieldModified ? 'modified' : ''}` }), jsx(Select, { label: '', optionsList: dropdownData, selectedOption: { value: dropdownValue, label: dropdownValue }, onChange: (option) => setDropdownValue(option.value) })] })) : (jsx("div", { className: "ff-label-text-field-without-dropdown", children: jsx(Input, { name: "input", type: "text", label: label ? label : '', disabled: false, error: isThrowingError, placeholder: placeholder ? placeholder : '', value: inputValue, onChange: handleTextFieldChange, className: `${className} 
               
               ${isTextFieldModified ? 'modified' : ''}` }) })), jsxs("div", { className: "ff-icon-container", children: [confirmIcon && (jsx(Tooltip, { title: "Confirm", placement: 'bottom', children: jsx(Icon, { color: "var(--label-edit-confirm-icon)", height: 20, width: 20, name: confirmIcon.name, disabled: disabled, className: `${disabled ? 'disabled-confirm-icon' : 'confirm-icon'}`, onClick: handleConfirm }) })), cancelIcon && (jsx(Tooltip, { title: "Cancel", placement: 'bottom', children: jsx(Icon, { color: "var(--label-edit-cancel-icon)", height: 12, width: 20, name: cancelIcon.name, className: "cancel-icon", onClick: handleCancel, ref: cancelRef }) }))] })] })) : (jsx(Tooltip, { title: tooltip?.tooltipTitle ? tooltip?.tooltipTitle : '', placement: 'bottom', children: showText && (jsx("span", { className: "display-text", onDoubleClick: handleDoubleClick, role: "button", onClick: handleClick, children: jsx(HighlightText, { text: inputValue, highlight: highlightText }) })) })), showError && isEditing && (jsx(Typography, { as: "p", fontSize: 8, className: "error-text", children: showError }))] }));
};

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