import { ChannelPreview } from "@ui/components/ChannelPreview";
import { CustomChannelHeader } from "@ui/components/CustomChannelHeader";
import { useEffect, useState } from "react";
import {
  Channel,
  ChannelList,
  MessageInput,
  MessageList,
  useChatContext,
  Window,
} from "stream-chat-react";
import { useChannelFromUrl } from "../hooks/channel";
import { useTablosList } from "../hooks/tablos";
import { useUser } from "../providers/UserStoreProvider";

export function ChatPage() {
  const user = useUser();
  const filters = { members: { $in: [user.id] }, type: "messaging" };

  const { client, channel, setActiveChannel } = useChatContext();
  const { channel: channelFromUrl, isChannelInUrl } = useChannelFromUrl(client);

  const { data: tablos } = useTablosList();
  const [isChannelListExpanded, setIsChannelListExpanded] = useState(false);

  const toggleChannelList = () => {
    setIsChannelListExpanded(!isChannelListExpanded);
  };

  useEffect(() => {
    if (channelFromUrl) {
      setActiveChannel(channelFromUrl);
    } else {
      setIsChannelListExpanded(true);
    }
  }, [channelFromUrl]);

  return (
    <div className="flex flex-col h-[calc(100vh-75px)] bg-gray-50 dark:bg-background">
      <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 shrink-0">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Discussions</h1>
      </div>
      <div className="flex flex-1 overflow-hidden">
        <div
          className={`border-r border-gray-200 dark:border-gray-600/50 bg-white dark:bg-gray-700/40 transition-all duration-300 ease-in-out overflow-hidden ${
            isChannelListExpanded ? "w-80" : "w-0"
          }`}
        >
          <ChannelList
            filters={filters}
            setActiveChannelOnMount={isChannelInUrl ? false : true}
            Preview={({
              displayTitle,
              channel,
              activeChannel,
              setActiveChannel,
              unread,
              latestMessagePreview,
            }) => (
              <ChannelPreview
                displayTitle={displayTitle}
                channel={channel}
                tablo={tablos?.find((t) => t.id === channel.id) ?? null}
                activeChannel={activeChannel}
                setActiveChannel={setActiveChannel}
                unreadCount={unread}
                latestMessagePreview={latestMessagePreview}
              />
            )}
          />
        </div>
        <div className="flex-1 bg-white dark:bg-gray-700/40">
          <Channel channel={channel}>
            <Window>
              <CustomChannelHeader
                tablos={tablos ?? []}
                onToggleChannelList={toggleChannelList}
                isChannelListExpanded={isChannelListExpanded}
              />
              <MessageList />
              <MessageInput />
            </Window>
          </Channel>
        </div>
      </div>
    </div>
  );
}
