import { type FormEvent, useRef, useState } from "react";

interface StagedFile {
  filename: string;
  workspace_path: string;
  mime_type: string;
  size: number;
}

interface ChatInputProps {
  onSend: (text: string, files?: { filename: string; size: number; mime_type: string; download_url: string }[]) => void;
  disabled: boolean;
  userId: string | null;
}

export function ChatInput({ onSend, disabled, userId }: ChatInputProps) {
  const [text, setText] = useState("");
  const [files, setFiles] = useState<StagedFile[]>([]);
  const fileRef = useRef<HTMLInputElement>(null);

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    const trimmed = text.trim();
    if (!trimmed && files.length === 0) return;
    const atts = files.length
      ? files.map((f) => ({
          filename: f.filename,
          size: f.size,
          mime_type: f.mime_type,
          download_url: "/files/" + f.workspace_path,
        }))
      : undefined;
    onSend(trimmed, atts);
    setText("");
    setFiles([]);
  };

  const handleFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file || !userId) return;
    const fd = new FormData();
    fd.append("file", file);
    try {
      const resp = await fetch("/upload?user_id=" + userId, { method: "POST", body: fd });
      const data = await resp.json();
      if (data.attachment_id) {
        setFiles((prev) => [...prev, {
          filename: file.name,
          workspace_path: data.workspace_path,
          mime_type: file.type,
          size: file.size,
        }]);
      }
    } catch (err) {
      console.error("upload", err);
    }
    e.target.value = "";
  };

  return (
    <div className="input-area">
      {files.length > 0 && (
        <div className="attach-bar">
          {files.map((f, i) => (
            <span key={i} className="attach-tag">
              📎 {f.filename}
              <span className="remove" onClick={() => setFiles((p) => p.filter((_, j) => j !== i))}>×</span>
            </span>
          ))}
        </div>
      )}
      <form className="chat-input" onSubmit={handleSubmit}>
        <button type="button" className="file-btn" onClick={() => fileRef.current?.click()} title="Прикрепить файл">
          📎
        </button>
        <input ref={fileRef} type="file" hidden onChange={handleFile} />
        <input
          type="text"
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Напишите сообщение..."
          disabled={disabled}
          autoFocus
        />
        <button type="submit" className="btn-send" disabled={disabled || (!text.trim() && files.length === 0)}>
          Отправить
        </button>
      </form>
    </div>
  );
}
