import './Input.css';
import { InputLogic } from './Input.js';
import { useRef, useState } from 'react';

function Input() {
  const { onSend, onUpload } = InputLogic();
  const [message, setMessage] = useState('');
  const fileInputRef = useRef(null);

  const handleSend = () => {
    const trimmed = message.trim();
    if (!trimmed) return;
    onSend?.(trimmed);
    setMessage('');
  };

  const handleFileChange = (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    onUpload?.(file);
    event.target.value = '';
  };

  return (
    <div className="input-container">
      <button
        type="button"
        className="upload-btn"
        onClick={() => fileInputRef.current?.click()}
        title="上传图片"
      >
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
        </svg>
      </button>

      <input
        className="input-text"
        type="text"
        placeholder="输入消息..."
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSend();
          }
        }}
      />

      <button
        type="button"
        className="send-btn"
        onClick={handleSend}
        disabled={!message.trim()}
        title="发送消息"
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <line x1="22" y1="2" x2="11" y2="13"></line>
          <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
        </svg>
      </button>

      <input
        type="file"
        ref={fileInputRef}
        className="file-input"
        onChange={handleFileChange}
        accept="image/*"
      />
    </div>
  );
}

export default Input;
