import React, { useState, useRef, useEffect } from "react";
import type { Message } from "../types";

interface ChatPaneProps {
  messages: Message[];
  onSend: (message: string) => void;
  isLoading: boolean;
  disabled: boolean;
  placeholder: string;
  collapsed: boolean;
  chatWidth: number;
  onToggleCollapse: () => void;
}

export function ChatPane({
  messages,
  onSend,
  isLoading,
  disabled,
  placeholder,
  collapsed,
  chatWidth,
  onToggleCollapse,
}: ChatPaneProps) {
  const [input, setInput] = useState("");
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);

  const handleSend = () => {
    if (!input.trim() || isLoading || disabled) return;
    onSend(input.trim());
    setInput("");
  };

  return (
    <div
      className="chat-pane"
      style={{ width: collapsed ? 28 : chatWidth }}
    >
      <div className="chat-header">
        {!collapsed && <span>Chat</span>}
        <button className="chat-collapse-btn" onClick={onToggleCollapse}>
          {collapsed ? "⟨" : "⟩"}
        </button>
      </div>

      {!collapsed && (
        <>
          <div className="chat-messages">
            {messages.map((msg) => (
              <div key={msg.id} className={`message ${msg.role}`}>
                <div className="message-content">{msg.content}</div>
              </div>
            ))}
            {isLoading && (
              <div className="message assistant loading">
                <div className="message-content">Thinking...</div>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          <div className="chat-input">
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) =>
                e.key === "Enter" && !e.shiftKey && handleSend()
              }
              placeholder={placeholder}
              disabled={disabled || isLoading}
            />
            <button
              onClick={handleSend}
              disabled={disabled || isLoading || !input.trim()}
            >
              Send
            </button>
          </div>
        </>
      )}
    </div>
  );
}
