import { ArrowUp, Square } from 'lucide-react';
import { useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

export function ChatComposer({
    value,
    onChange,
    onSubmit,
    onCancel,
    disabled,
    streaming,
}: {
    value: string;
    onChange: (value: string) => void;
    onSubmit: () => void;
    onCancel?: () => void;
    disabled?: boolean;
    streaming?: boolean;
}) {
    const ref = useRef<HTMLTextAreaElement>(null);

    useEffect(() => {
        const el = ref.current;

        if (!el) {
            return;
        }

        el.style.height = '0px';
        el.style.height = `${Math.min(el.scrollHeight, 180)}px`;
    }, [value]);

    return (
        <form
            className="border-t border-border bg-background/95 p-4 backdrop-blur"
            onSubmit={(event) => {
                event.preventDefault();
                onSubmit();
            }}
        >
            <div className="mx-auto flex w-full max-w-3xl items-end gap-2 rounded-2xl border border-border bg-card p-2 shadow-xs">
                <textarea
                    ref={ref}
                    value={value}
                    disabled={disabled}
                    rows={1}
                    placeholder="Ask about revenue, expenses, cash flow, or forecasts…"
                    className={cn(
                        'max-h-44 min-h-11 flex-1 resize-none bg-transparent px-3 py-2.5 text-sm outline-none placeholder:text-muted-foreground disabled:opacity-50',
                    )}
                    onChange={(event) => onChange(event.target.value)}
                    onKeyDown={(event) => {
                        if (event.key === 'Enter' && !event.shiftKey) {
                            event.preventDefault();
                            onSubmit();
                        }
                    }}
                />
                <Button
                    type={streaming ? 'button' : 'submit'}
                    size="icon"
                    disabled={
                        (disabled && !streaming) ||
                        (!streaming && value.trim() === '')
                    }
                    aria-label={streaming ? 'Stop generating' : 'Send message'}
                    onClick={streaming ? onCancel : undefined}
                    className="shrink-0 rounded-xl"
                >
                    {streaming ? (
                        <Square className="size-3.5 fill-current" />
                    ) : (
                        <ArrowUp className="size-4" />
                    )}
                </Button>
            </div>
        </form>
    );
}
