import React, { useEffect } from "react";
import Message from "./Message";
import MessageInput from "./MessageInput";
import { useMatrix } from "../matrix/MatrixProvider.jsx";
import DemoLoginButton from "./DemoLoginButton.jsx";

// Default room to join (replace with your Matrix room ID)
const DEFAULT_ROOM_ID = "!foundation:matrix.org";

export default function ChatArea() {
  const { messages, joinRoom, currentRoomId, user, login, loading } = useMatrix();

  // Join the default room on login
  useEffect(() => {
    if (user && !currentRoomId) {
      joinRoom(DEFAULT_ROOM_ID);
    }
  }, [user, currentRoomId, joinRoom]);

  // Demo login handler
  const handleDemoLogin = () => {
    // Use a public Matrix test account or a known demo account
    // You can change these credentials as needed
    login("@mrpiglr:matrix.org", "Max!FTW2023!", "https://matrix.org");
  };

  if (!user) {
    return (
      <div className="chat-area flex flex-col flex-1 bg-[#0a0a0a] items-center justify-center">
        <DemoLoginButton onDemoLogin={handleDemoLogin} />
        {loading && <div className="text-gray-400 mt-4">Logging in as demo user...</div>}
      </div>
    );
  }

  return (
    <div className="chat-area flex flex-col flex-1 bg-[#0a0a0a]">
      {/* Chat Header */}
      <div className="chat-header px-5 py-4 border-b border-[#1a1a1a] flex items-center gap-3">
        <span className="channel-name-header flex-1 font-bold text-base"># general</span>
        <div className="chat-tools flex gap-4 text-sm text-gray-500">
          <span className="chat-tool cursor-pointer hover:text-blue-500">🔔</span>
          <span className="chat-tool cursor-pointer hover:text-blue-500">📌</span>
          <span className="chat-tool cursor-pointer hover:text-blue-500">👥 128</span>
          <span className="chat-tool cursor-pointer hover:text-blue-500">🔍</span>
        </div>
      </div>
      {/* Messages */}
      <div className="chat-messages flex-1 overflow-y-auto px-5 py-5">
        {messages && messages.length > 0 ? (
          messages.map((msg, i) => (
            <Message key={i} {...matrixToMessageProps(msg)} />
          ))
        ) : (
          <div className="text-gray-500 text-center">No messages yet.</div>
        )}
      </div>
      {/* Message Input */}
      <div className="message-input-container px-5 py-5 border-t border-[#1a1a1a]">
        <MessageInput />
      </div>
    </div>

  );
}


// Helper to convert Matrix event to Message props
function matrixToMessageProps(event) {
  if (!event) return {};
  if (event.type === "m.room.message") {
    return {
      type: "user",
      author: event.sender?.split(":")[0]?.replace("@", "") || "User",
      text: event.content?.body || "",
      time: new Date(event.origin_server_ts).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
      avatar: event.sender?.charAt(1)?.toUpperCase() || "U",
      avatarBg: "from-blue-600 to-blue-900",
    };
  }
  // Add system message mapping if needed
  return { type: "system", label: "MATRIX", text: JSON.stringify(event), className: "foundation" };
}
