"use client";

import { useState, useRef, type KeyboardEvent } from "react";

export interface ComposerProps {
  disabled?: boolean;
  onSend: (text: string) => void;
  onAbort?: () => void;
  busy?: boolean;
}

export function Composer({ disabled, onSend, onAbort, busy }: ComposerProps) {
  const [text, setText] = useState("");
  const taRef = useRef<HTMLTextAreaElement>(null);

  function submit() {
    const trimmed = text.trim();
    if (!trimmed || disabled) return;
    onSend(trimmed);
    setText("");
    requestAnimationFrame(() => taRef.current?.focus());
  }

  function handleKey(e: KeyboardEvent<HTMLTextAreaElement>) {
    if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
      e.preventDefault();
      submit();
    }
  }

  return (
    <div className="border-t border-neutral-800 bg-neutral-950/80 px-4 py-3 backdrop-blur">
      <div className="mx-auto flex max-w-3xl gap-2">
        <textarea
          ref={taRef}
          value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={handleKey}
          disabled={disabled}
          rows={2}
          placeholder={
            disabled ? "连接中…" : "输入消息（Enter 发送，Shift+Enter 换行）"
          }
          className="flex-1 resize-none rounded-lg border border-neutral-800 bg-neutral-900 px-3 py-2 text-sm text-neutral-100 placeholder:text-neutral-600 focus:border-sky-700 focus:outline-none disabled:opacity-50"
        />
        {busy && onAbort ? (
          <button
            type="button"
            onClick={onAbort}
            className="rounded-lg border border-red-800 bg-red-950 px-4 text-sm font-medium text-red-100 hover:bg-red-900"
          >
            中止
          </button>
        ) : (
          <button
            type="button"
            onClick={submit}
            disabled={disabled || !text.trim()}
            className="rounded-lg bg-sky-600 px-4 text-sm font-medium text-white hover:bg-sky-500 disabled:bg-neutral-800 disabled:text-neutral-600"
          >
            发送
          </button>
        )}
      </div>
    </div>
  );
}
