import { forwardRef, useState, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

interface CommentFormProps {
  onSubmit: (body: string) => void;
  onCancel: () => void;
  placeholder?: string;
  submitLabel?: string;
  initialValue?: string;
}

export const CommentForm = forwardRef<HTMLTextAreaElement, CommentFormProps>(
  function CommentForm(
    { onSubmit, onCancel, placeholder = "Write a comment...", submitLabel = "Comment", initialValue = "" },
    ref
  ) {
    const [body, setBody] = useState(initialValue);

    const handleSubmit = useCallback(() => {
      const trimmed = body.trim();
      if (!trimmed) return;
      onSubmit(trimmed);
      setBody("");
    }, [body, onSubmit]);

    const handleKeyDown = useCallback(
      (e: React.KeyboardEvent) => {
        if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
          e.preventDefault();
          handleSubmit();
        }
        if (e.key === "Escape") {
          onCancel();
        }
      },
      [handleSubmit, onCancel]
    );

    return (
      <div className="space-y-2">
        <Textarea
          ref={ref}
          value={body}
          onChange={(e) => setBody(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          className="min-h-[60px] text-xs resize-none"
          rows={2}
        />
        <div className="flex items-center justify-between">
          <span className="text-[10px] text-muted-foreground">
            Cmd+Enter to submit, Esc to cancel
          </span>
          <div className="flex gap-1.5">
            <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={onCancel}>
              Cancel
            </Button>
            <Button
              size="sm"
              className="h-7 text-xs"
              onClick={handleSubmit}
              disabled={!body.trim()}
            >
              {submitLabel}
            </Button>
          </div>
        </div>
      </div>
    );
  }
);
