import * as React from 'react';
import { cn } from '../utils/cn';
import { Send } from 'lucide-react';

export interface ChatInputProps {
  placeholder?: string;
  maxLength?: number;
  disabled?: boolean;
  /** Called when the user submits a message. Return false to indicate failure. */
  onSubmit: (text: string) => boolean | void;
  /** Called when send fails (onSubmit returns false). */
  onSendError?: (text: string) => void;
  className?: string;
}

const ChatInput = React.forwardRef<HTMLDivElement, ChatInputProps>(
  ({ placeholder = 'Type a message...', maxLength = 4000, disabled, onSubmit, onSendError, className }, ref) => {
    const [value, setValue] = React.useState('');
    const textareaRef = React.useRef<HTMLTextAreaElement>(null);

    const adjustHeight = React.useCallback(() => {
      const textarea = textareaRef.current;
      if (textarea) {
        textarea.style.height = 'auto';
        textarea.style.height = `${Math.min(textarea.scrollHeight, 200)}px`;
      }
    }, []);

    React.useEffect(() => {
      adjustHeight();
    }, [value, adjustHeight]);

    const handleSubmit = React.useCallback(() => {
      const trimmed = value.trim();
      if (trimmed && !disabled) {
        const result = onSubmit(trimmed);
        if (result === false) {
          // Send failed - notify via callback
          onSendError?.(trimmed);
          return;
        }
        setValue('');
        if (textareaRef.current) {
          textareaRef.current.style.height = 'auto';
        }
      }
    }, [value, disabled, onSubmit, onSendError]);

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

    const charCount = value.length;
    const isNearLimit = charCount > maxLength * 0.9;
    const isOverLimit = charCount > maxLength;

    return (
      <div
        ref={ref}
        className={cn(
          'relative flex items-end gap-2 rounded-xl border border-[var(--border)] bg-[var(--surface-100)] p-2 transition-colors focus-within:border-[var(--accent)]',
          disabled && 'opacity-50 cursor-not-allowed',
          className
        )}
      >
        <textarea
          ref={textareaRef}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          disabled={disabled}
          rows={1}
          className={cn(
            'flex-1 resize-none bg-transparent text-sm text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none disabled:cursor-not-allowed',
            'min-h-[24px] max-h-[200px] py-1 px-2'
          )}
        />

        <div className="flex items-center gap-2 flex-shrink-0">
          {isNearLimit && (
            <span
              className={cn(
                'text-xs tabular-nums',
                isOverLimit ? 'text-[var(--error)]' : 'text-[var(--text-muted)]'
              )}
            >
              {charCount}/{maxLength}
            </span>
          )}

          <button
            type="button"
            onClick={handleSubmit}
            disabled={disabled || !value.trim() || isOverLimit}
            className={cn(
              'flex items-center justify-center w-8 h-8 rounded-lg transition-colors',
              'bg-[var(--accent)] text-[var(--accent-foreground)]',
              'hover:bg-[var(--accent-hover)]',
              'disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-[var(--accent)]'
            )}
          >
            <Send className="w-4 h-4" />
          </button>
        </div>
      </div>
    );
  }
);
ChatInput.displayName = 'ChatInput';

export { ChatInput };
