import { useCallback, useEffect, useRef, useState } from 'react';

interface InlineReviewEditorProps {
  initialBody?: string;
  onSave: (body: string) => void;
  onCancel: () => void;
}

export function InlineReviewEditor({ initialBody = '', onSave, onCancel }: InlineReviewEditorProps) {
  const [text, setText] = useState(initialBody);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    textareaRef.current?.focus();
  }, []);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        onCancel();
      }
      if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && text.trim()) {
        onSave(text.trim());
      }
    },
    [onCancel, onSave, text],
  );

  return (
    <div className="mx-2 my-1 rounded border border-border/80 bg-popover p-2 shadow-sm">
      <textarea
        ref={textareaRef}
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={handleKeyDown}
        placeholder="Add a comment..."
        rows={3}
        className="w-full resize-none bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 outline-none"
      />
      <div className="flex items-center justify-end gap-1.5 mt-1.5 border-t border-border/40 pt-1.5">
        <button
          type="button"
          onClick={onCancel}
          className="text-xs px-2 py-1 rounded hover:bg-muted text-muted-foreground"
        >
          Cancel
        </button>
        <button
          type="button"
          disabled={!text.trim()}
          onClick={() => onSave(text.trim())}
          className="text-xs px-2 py-1 rounded bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-40"
        >
          Save
        </button>
      </div>
    </div>
  );
}
