import { ChatMessages, useChat, useChatUnread } from "@xtablo/tablo-views";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { ChatChannelPreview } from "../components/ChatChannelPreview";
import { ChatHeader } from "../components/ChatHeader";
import { useTabloMembers, useTablosList } from "../hooks/tablos";
import { useUser } from "../providers/UserStoreProvider";

export function ChatPage() {
  const { t } = useTranslation("chat");
  const user = useUser();
  const { channelId } = useParams();
  const navigate = useNavigate();
  const { data: tablos } = useTablosList();
  const { getUnreadCount } = useChatUnread();
  const [isChannelListExpanded, setIsChannelListExpanded] = useState(!channelId);

  const {
    messages,
    sendMessage,
    sendTyping,
    typingUsers,
    onlineUsers,
    loadMoreMessages,
    hasMoreMessages,
    markAsRead,
  } = useChat(channelId);

  const { data: members = [] } = useTabloMembers(channelId ?? "");
  const activeTablo = tablos?.find((t) => t.id === channelId) ?? null;

  // Mark as read when channel is focused
  useEffect(() => {
    if (channelId && messages.length > 0) {
      markAsRead();
    }
  }, [channelId, messages.length, markAsRead]);

  const handleChannelSelect = (tabloId: string) => {
    navigate(`/chat/${tabloId}`);
  };

  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">{t("pageTitle")}</h1>
      </div>
      <div className="flex flex-1 overflow-hidden">
        {/* Channel list sidebar */}
        <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"
          }`}
        >
          <div className="overflow-y-auto h-full">
            {tablos?.map((tablo) => (
              <ChatChannelPreview
                key={tablo.id}
                tablo={tablo}
                isActive={channelId === tablo.id}
                onClick={() => handleChannelSelect(tablo.id)}
                unreadCount={getUnreadCount(tablo.id)}
                isOnline={onlineUsers.some((uid) => uid !== user.id)}
              />
            ))}
          </div>
        </div>

        {/* Chat area */}
        <div className="flex-1 flex flex-col bg-white dark:bg-gray-700/40">
          {channelId && activeTablo ? (
            <>
              <ChatHeader
                tablo={activeTablo}
                onToggleChannelList={() => setIsChannelListExpanded(!isChannelListExpanded)}
                isChannelListExpanded={isChannelListExpanded}
                onlineUsers={onlineUsers}
              />
              <div className="flex-1 overflow-hidden">
                <ChatMessages
                  messages={messages}
                  currentUserId={user.id}
                  members={members}
                  typingUsers={typingUsers}
                  hasMoreMessages={hasMoreMessages}
                  onLoadMore={loadMoreMessages}
                  onSend={sendMessage}
                  onTyping={sendTyping}
                  placeholder={t("placeholder")}
                />
              </div>
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center text-gray-500 dark:text-gray-400">
              {t("selectConversation")}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
