import { jsx, jsxs } from "react/jsx-runtime";
import { Box, TextareaAutosize } from "@mui/material";
import { styled } from "@mui/material/styles";
import apollo_core, { FontVariantToken } from "@uipath/apollo-core";
import react, { useCallback, useRef, useState } from "react";
import { ApTypography } from "../ap-typography/index.js";
const StyledTextareaAutosize = styled(TextareaAutosize, {
    shouldForwardProp: (prop)=>'hasError' !== prop && 'width' !== prop && 'resize' !== prop
})(({ hasError, width, resize = 'vertical' })=>({
        width: width || '100%',
        padding: `${apollo_core.Spacing.SpacingXs} ${apollo_core.Spacing.SpacingS}`,
        fontSize: apollo_core.FontFamily.FontMSize,
        lineHeight: apollo_core.FontFamily.FontMLineHeight,
        fontFamily: apollo_core.FontFamily.FontMFamily,
        color: 'var(--color-foreground)',
        backgroundColor: 'var(--color-background)',
        border: `${apollo_core.Border.BorderThickS} solid ${hasError ? 'var(--color-error-icon)' : 'var(--color-border)'}`,
        borderRadius: apollo_core.Border.BorderRadiusS,
        resize,
        outline: 'none',
        transition: 'border-color 0.2s ease-in-out',
        '&::placeholder': {
            color: 'var(--color-foreground-de-emp)'
        },
        '&:hover:not(:disabled):not(:focus)': {
            borderColor: hasError ? 'var(--color-error-icon)' : 'var(--color-border)'
        },
        '&:focus': {
            borderColor: hasError ? 'var(--color-error-icon)' : 'var(--color-focus-indicator)',
            boxShadow: hasError ? `0 0 0 ${apollo_core.Border.BorderThickS} var(--color-error-icon)` : `0 0 0 ${apollo_core.Border.BorderThickS} var(--color-focus-indicator)`
        },
        '&:disabled': {
            backgroundColor: 'var(--color-background-disabled)',
            color: 'var(--color-foreground-de-emp)',
            cursor: 'not-allowed'
        },
        '&:read-only': {
            backgroundColor: 'var(--color-background-secondary)',
            cursor: 'default'
        }
    }));
const ApTextArea = /*#__PURE__*/ react.forwardRef(({ label, value, placeholder, readOnly = false, required = false, disabled = false, errorMessage, helperText, width, rows = 4, minRows, maxRows, characterLimit, resize = 'vertical', dataTestid, onChange, ...restProps }, ref)=>{
    const [cursorPosition, setCursorPosition] = useState(null);
    const textareaRef = useRef(null);
    const hasError = Boolean(errorMessage);
    const stringValue = 'string' == typeof value ? value : value?.toString() || '';
    const currentLength = stringValue.length;
    const showCharacterCounter = void 0 !== characterLimit;
    const isOverLimit = void 0 !== characterLimit && currentLength > characterLimit;
    const handleChange = useCallback((event)=>{
        const newValue = event.target.value;
        const textarea = event.target;
        if (void 0 !== characterLimit && newValue.length > characterLimit) {
            const start = textarea.selectionStart;
            const trimmedValue = newValue.slice(0, characterLimit);
            event.target.value = trimmedValue;
            setCursorPosition(Math.min(start, characterLimit));
        }
        onChange?.(event);
    }, [
        characterLimit,
        onChange
    ]);
    react.useEffect(()=>{
        if (null !== cursorPosition && textareaRef.current) {
            textareaRef.current.setSelectionRange(cursorPosition, cursorPosition);
            setCursorPosition(null);
        }
    }, [
        cursorPosition
    ]);
    const combinedRef = useCallback((node)=>{
        textareaRef.current = node;
        if ('function' == typeof ref) ref(node);
        else if (ref) ref.current = node;
    }, [
        ref
    ]);
    const labelId = label ? `textarea-label-${dataTestid || 'default'}` : void 0;
    const helperId = helperText || errorMessage ? `textarea-helper-${dataTestid || 'default'}` : void 0;
    return /*#__PURE__*/ jsxs(Box, {
        sx: {
            width: width || '100%'
        },
        children: [
            label && /*#__PURE__*/ jsx(Box, {
                sx: {
                    marginBottom: apollo_core.Spacing.SpacingMicro
                },
                children: /*#__PURE__*/ jsxs(ApTypography, {
                    variant: FontVariantToken.fontSizeM,
                    id: labelId,
                    style: {
                        color: 'var(--color-foreground)'
                    },
                    children: [
                        label,
                        required && /*#__PURE__*/ jsx(Box, {
                            component: "span",
                            sx: {
                                color: 'var(--color-error-text)',
                                marginLeft: apollo_core.Spacing.SpacingMicro
                            },
                            children: "*"
                        })
                    ]
                })
            }),
            /*#__PURE__*/ jsx(StyledTextareaAutosize, {
                ref: combinedRef,
                value: stringValue,
                placeholder: placeholder,
                readOnly: readOnly,
                disabled: disabled,
                hasError: hasError,
                width: width,
                minRows: void 0 !== minRows ? minRows : rows,
                maxRows: void 0 !== maxRows ? maxRows : void 0 !== rows ? rows : void 0,
                resize: resize,
                onChange: handleChange,
                "data-testid": dataTestid,
                "aria-labelledby": labelId,
                "aria-describedby": helperId,
                "aria-invalid": hasError,
                "aria-required": required,
                ...restProps
            }),
            (errorMessage || helperText || showCharacterCounter) && /*#__PURE__*/ jsxs(Box, {
                sx: {
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'flex-start',
                    marginTop: apollo_core.Spacing.SpacingMicro,
                    gap: apollo_core.Spacing.SpacingXs
                },
                children: [
                    /*#__PURE__*/ jsxs(Box, {
                        sx: {
                            flex: 1
                        },
                        children: [
                            errorMessage && /*#__PURE__*/ jsx(ApTypography, {
                                variant: FontVariantToken.fontSizeS,
                                id: helperId,
                                style: {
                                    color: 'var(--color-error-text)'
                                },
                                children: errorMessage
                            }),
                            !errorMessage && helperText && /*#__PURE__*/ jsx(ApTypography, {
                                variant: FontVariantToken.fontSizeS,
                                id: helperId,
                                style: {
                                    color: 'var(--color-foreground-de-emp)'
                                },
                                children: helperText
                            })
                        ]
                    }),
                    showCharacterCounter && /*#__PURE__*/ jsxs(ApTypography, {
                        variant: FontVariantToken.fontSizeS,
                        style: {
                            color: isOverLimit ? 'var(--color-error-text)' : 'var(--color-foreground-de-emp)',
                            whiteSpace: 'nowrap'
                        },
                        children: [
                            currentLength,
                            "/",
                            characterLimit
                        ]
                    })
                ]
            })
        ]
    });
});
ApTextArea.displayName = 'ApTextArea';
export { ApTextArea };
