import { useChatStore } from '@/stores/chatStore';
import { useEffect, type FC } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { ChatSidebar } from './ChatSidebar';
import { MessageInput } from './MessageInput';
import { MessageList } from './MessageList';
import { NavBar } from './Navbar';
import { UsersSidebar } from './UsersSidebar';

export const ChatApp: FC = () => {
  const { roomId } = useParams<{ roomId: string }>();
  const { setSelectedRoom, selectedRoomId } = useChatStore();
  const navigate = useNavigate();

  useEffect(() => {
    if (roomId) {
      setSelectedRoom(roomId);
    }
  }, [roomId, setSelectedRoom]);

  useEffect(() => {
    if (selectedRoomId && selectedRoomId !== roomId) {
      navigate(`/room/${selectedRoomId}`);
    }
  }, [selectedRoomId, navigate, roomId]);

  return (
    <div className="flex h-screen bg-white">
      <ChatSidebar
        selectedRoomId={roomId || selectedRoomId}
        onRoomSelect={setSelectedRoom}
      />
      <div className="flex-1 flex flex-col">
        <NavBar />
        <div className="flex-1 flex flex-col overflow-hidden">
          {roomId ? (
            <>
              <div className="flex-1 flex overflow-hidden">
                <div className="flex-1 flex flex-col overflow-hidden">
                  <MessageList roomId={roomId} />
                  <MessageInput roomId={roomId} />
                </div>
                <UsersSidebar roomId={roomId} />
              </div>
            </>
          ) : (
            <div className="flex-1 flex items-center justify-center text-gray-500 dark:bg-gray-800 dark:text-gray-400">
              <div className="text-center">
                <h2 className="text-xl font-semibold mb-2">
                  Welcome to Chat App
                </h2>
                <p>Select a chat room to start messaging</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
