import { useCallback, useContext } from "preact/hooks";
import { StateContext } from "../contexts/state";
import { LLMContext } from "../contexts/llm";
import { AutoTextarea } from "./autoTextarea";

export const Input = () => {
    const { input, setInput, addMessage, continueMessage } = useContext(StateContext);
    const { generating, stopGeneration } = useContext(LLMContext);

    const handleSend = useCallback(async () => {
        if (!generating) {
            const newInput = input.trim();
            if (newInput) {
                addMessage(newInput, 'user', true);
                setInput('');
            } else {
                continueMessage();
            }
        }
    }, [input, setInput, generating]);

    const handleKeyDown = useCallback((e: KeyboardEvent) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
        }
    }, [handleSend]);

    return (
        <div class="chat-input">
            <AutoTextarea onInput={setInput} onKeyDown={handleKeyDown} value={input} />
            {generating
                ? <button onClick={stopGeneration}>Stop</button>
                : <button onClick={handleSend}>{input ? 'Send' : 'Continue'}</button>
            }
        </div>
    );
}