import LeftPanel from "./LeftPanel"
import { Pb } from "../EspaceMembres"
import { useContext, useEffect, useState } from "preact/hooks"
import Message from "./Chat/Message"
import type { MessageExpand } from "./Chat/Message"

function Chat() {
  const pb = useContext(Pb);
  const [messages, setMessages] = useState<MessageExpand[]>([]);

  useEffect(() => {
    async function getMessages() {
      const data = await pb.collection('messages').getFullList<MessageExpand>({
        expand: 'author,users(avatar)'
      });
      if (!data) return;
      setMessages(data);
    }

    getMessages();
  }, [pb]);

  return (
    <div className="w-full">
      {messages.map((message) => (
        <Message message={message} />
      ))}
    </div>
  )
}

export default function Home() {
  return (
    <div className="flex min-h-full flex-grow">
      <LeftPanel />
      <Chat />
    </div>
  )
}
