import { FaCog } from "react-icons/fa";
import { Pb } from "../../EspaceMembres";
import { CurrentChannel } from "../Home";
import { useContext, useEffect, useState } from "preact/hooks";
import type { ChannelsResponse } from "../../../types/pb_types";

export default function Channels() {
  const pb = useContext(Pb);
  const { set } = useContext(CurrentChannel);

  const [channels, setChannels] = useState<Array<ChannelsResponse>>([]);
  useEffect(() => {
    pb.collection('channels').getFullList<ChannelsResponse>().then((data) => {
      if (!data) return;
      setChannels(data);
      set({ name: data[0].name ?? '', id: data[0].id ?? ''});
    });
  }, []);

  const selectChannel = (channel: { name: string, id: string }) => {
    set(channel);
  }

  return (
    <div className="flex flex-col flex-grow border-b-2 border-b-gray-200">
      <div className="flex justify-between items-center p-4">
        <p className="flex-grow text-gray-500 font-medium text-xl">
          Canaux
        </p>
        <button className="px-1 pb-1 leading-none transition-all text-gray-400 hover:text-gray-500 hover:bg-gray-100 text-xl border border-gray-300 rounded-md">+</button>
      </div>
      <ul>
        {channels.map((channel) => (
          <li className="p-2 hover:bg-gray-100 cursor-pointer text-xl flex items-center" key={channel} onClick={() => selectChannel({ name: channel.name ?? '', id: channel.id ?? '' })}>
            <p className="flex-grow">
              <span className="text-gray-400">#</span> {channel.name}
            </p>
            <FaCog className="transition hover:text-gray-700" />
          </li>
        ))}
      </ul>
    </div>
  )
}
