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

export const CurrentChannel = createContext({
  get: () => { return { name: '', id: '' } },
  set: (channel: { name: string, id: string }) => { }
});

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);
    }

    document.addEventListener('newMessage', getMessages);

    getMessages();
  }, [pb]);

  return (
    <div className="w-full min-h-full max-h-full bg-grey flex flex-col justify-between overflow-y-hidden">
      <ScrollToBottom className="message-container flex flex-col gap-4 w-full overflow-y-scroll overflow-x-hidden pt-4 pb-6 px-2 md:px-0">
        {messages.map((message) => (
          <Message message={message} />
        ))}
      </ScrollToBottom>
      <div className="flex justify-center">
        <div className="w-full max-w-3xl">
          <NewMessage />
        </div>
      </div>
    </div>
  )
}

export default function Home() {
  const [channel, setChannel] = useState({ name: '', id: ''});

  useEffect(() => {
    const channel = localStorage.getItem('channel');
    if (channel) {
      setChannel(JSON.parse(channel));
    }
  }, []);

  useEffect(() => {
    if (!channel.id) return;
    localStorage.setItem('channel', JSON.stringify(channel));
    console.log(channel);
  }, [channel]);

  return (
    <div className="flex min-h-full max-h-[90vh] flex-grow overflow-y-hidden">
      <CurrentChannel.Provider value={{ get: () => channel, set: setChannel }}>
        <LeftPanel />
        <Chat />
      </CurrentChannel.Provider>
    </div>
  )
}
