"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { ArrowUp, Square } from "lucide-react";
import { useShortcut } from "@/hooks/use-keyboard";

interface Props {
  onSend: (text: string) => void;
  onStop: () => void;
  isStreaming: boolean;
}

export function ChatInput({ onSend, onStop, isStreaming }: Props) {
  const [value, setValue] = React.useState("");
  const ref = React.useRef<HTMLTextAreaElement>(null);

  useShortcut("mod+/", (e) => {
    e.preventDefault();
    ref.current?.focus();
  });

  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    el.style.height = "0px";
    el.style.height = Math.min(el.scrollHeight, 240) + "px";
  }, [value]);

  function submit() {
    const text = value.trim();
    if (!text || isStreaming) return;
    onSend(text);
    setValue("");
  }

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

  return (
    <div className="shrink-0 px-4 pb-4 pt-2">
      <div className="mx-auto max-w-3xl">
        <div className="rounded-2xl border border-border bg-card shadow-sm focus-within:ring-2 focus-within:ring-ring/40">
          <Textarea
            ref={ref}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onKeyDown={onKeyDown}
            placeholder="Message…"
            className="min-h-[56px] resize-none border-0 bg-transparent px-4 py-3 text-[0.975rem] shadow-none focus-visible:ring-0"
            rows={1}
          />
          <div className="flex items-center justify-between px-2 pb-2">
            <span className="pl-2 text-[11px] text-muted-foreground">
              Enter to send, Shift+Enter for newline · ⌘/ to focus
            </span>
            {isStreaming ? (
              <Button
                size="icon"
                variant="destructive"
                onClick={onStop}
                className="rounded-full"
                aria-label="Stop"
              >
                <Square className="!h-3 !w-3 fill-current" />
              </Button>
            ) : (
              <Button
                size="icon"
                onClick={submit}
                disabled={!value.trim()}
                className="rounded-full"
                aria-label="Send"
              >
                <ArrowUp />
              </Button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
