import React, { useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { ArrowUp } from 'lucide-react';

/**
 * Rounded message composer: auto-growing textarea with an inline send button.
 * Enter sends, Shift+Enter inserts a new line.
 */
const Composer = ({ value, onChange, onSubmit, placeholder, disabled = false, isLoading = false, autoFocus = false, className = '' }) => {
    const textareaRef = useRef(null);

    useEffect(() => {
        const el = textareaRef.current;
        if (!el) return;
        el.style.height = 'auto';
        el.style.height = `${Math.min(el.scrollHeight, 120)}px`;
    }, [value]);

    useEffect(() => {
        if (autoFocus && textareaRef.current && window.innerWidth > 450) {
            textareaRef.current.focus();
        }
    }, [autoFocus]);

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
            e.preventDefault();
            onSubmit(e);
        }
    };

    const canSend = !disabled && !isLoading && value.trim().length > 0;

    return (
        <form className={`aisk-composer ${className}`} onSubmit={onSubmit}>
            <textarea
                ref={textareaRef}
                rows={1}
                value={value}
                onChange={(e) => onChange(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={placeholder}
                disabled={disabled}
                name="input"
                aria-label={__( 'Message', 'aisk-ai-chat' )}
            />
            <button
                type="submit"
                className="aisk-composer-send"
                disabled={!canSend}
                aria-label={__( 'Send message', 'aisk-ai-chat' )}
            >
                <ArrowUp size={18} strokeWidth={2.5} />
            </button>
        </form>
    );
};

export default Composer;
