import { forwardRef, ForwardedRef, useRef } from 'react';

import { styled } from '../../stitches.config';

import { useValue } from '../../hooks';
import {
    BaseFormInputStyles,
    BaseFormInput,
    BaseFormInputProps,
} from '../internal';

const StyledFormInput = styled(BaseFormInput, BaseFormInputStyles, {
    cursor: 'text',
    variants: {
        size: {
            sm: {
                padding: '$2 $2',
                height: '$space$12',
            },
            md: {
                padding: '$2 $2',
                height: '$space$20',
            },
            lg: {
                padding: '$2 $2',
                height: '$space$32',
            },
        },
    },
});

const StyledTextarea = styled('textarea', {
    backgroundColor: 'transparent',
    height: '$space$full',
    outline: 'none',
    width: '$space$full',
    resize: 'none',
});

export interface TextareaProps extends BaseFormInputProps<string> {
    /** Placeholder to show when there is no value */
    placeholder?: string;

    /** Specifies autocomplete on the textarea */
    autoComplete?: HTMLTextAreaElement['autocomplete'];

    /** Props to pass to the textarea */
    textareaProps?: React.InputHTMLAttributes<HTMLTextAreaElement>;
}

/**
 * Textarea component
 */
const _Textarea = (
    props: TextareaProps,
    ref: ForwardedRef<HTMLDivElement>,
): JSX.Element => {
    const {
        id,
        value,
        defaultValue,
        onChange = () => null,
        placeholder,
        autoComplete = 'off',
        textareaProps = {},
        disabled = false,
        ...otherProps
    } = props;

    // store the input in a ref
    const textareaRef = useRef<HTMLTextAreaElement | null>(null);

    // manage the internal value
    const [internalValue, setInternalValue] = useValue({
        initialValue: '',
        value: value,
        defaultValue: defaultValue,
        onChange: onChange,
    });

    return (
        <StyledFormInput
            ref={ref}
            focusRef={textareaRef}
            disabled={disabled}
            {...otherProps}
        >
            <StyledTextarea
                ref={textareaRef}
                id={id}
                value={internalValue}
                disabled={disabled}
                onChange={(event: React.ChangeEvent<HTMLTextAreaElement>) => {
                    if (disabled) {
                        return;
                    }

                    setInternalValue(event.target.value);
                }}
                placeholder={placeholder}
                autoComplete={autoComplete}
                {...textareaProps}
            />
        </StyledFormInput>
    );
};

export const Textarea = forwardRef(_Textarea) as (
    props: TextareaProps & {
        ref?: ForwardedRef<HTMLDivElement>;
    },
) => ReturnType<typeof _Textarea>;
