import * as React from 'react';
import { Box } from '../Flex';
import clsx from 'clsx';
import { twMerge } from '../../twMerge';
export const baseClassName = 'ab-Textarea';
const Textarea = React.forwardRef((props, ref) => {
    const internalRef = React.useRef(null);
    let { disabled, autoResizeOnFocus, className, ...textareaProps } = props;
    const initialHeight = React.useRef(null);
    let type = 'text';
    if (textareaProps && textareaProps.type) {
        type = textareaProps.type;
    }
    if (type === 'string') {
        type = 'text';
    }
    const expandToFitContent = () => {
        if (autoResizeOnFocus && initialHeight.current !== null && internalRef.current) {
            internalRef.current.style.height = `0px`; // makes sure it shrinks when needed
            const height = internalRef.current.scrollHeight;
            internalRef.current.style.height = `${height}px`;
        }
    };
    const shrinkToInitialHeight = () => {
        if (autoResizeOnFocus) {
            internalRef.current.style.height = `${initialHeight.current}px`;
        }
    };
    return (React.createElement(Box, { ...textareaProps, onFocus: (e) => {
            expandToFitContent();
            props.onFocus?.(e);
            if (internalRef.current && initialHeight.current === null) {
                const height = internalRef.current.getBoundingClientRect().height;
                initialHeight.current = height;
            }
        }, onBlur: (e) => {
            shrinkToInitialHeight();
            props.onBlur?.(e);
        }, ref: (elRef) => {
            // SAVE INITIAL HEIGHT
            // if (elRef && initialHeight.current === null) {
            //   const height = elRef.getBoundingClientRect().height;
            //   initialHeight.current = isNaN(height) ? 'auto' : height;
            // }
            // SAVE REF
            if (internalRef) {
                internalRef.current = elRef;
            }
            // CALL EXTERNAL REF
            if (ref) {
                if (typeof ref === 'function') {
                    ref(elRef);
                }
                else {
                    ref.current = elRef;
                }
            }
        }, onChange: (e) => {
            expandToFitContent();
            props.onChange && props.onChange(e);
        }, as: "textarea", type: type, disabled: disabled, className: twMerge(clsx(baseClassName, disabled ? `${baseClassName}--disabled` : ''), className), spellCheck: false }));
});
export default Textarea;
