import { useAuthStore } from '@/stores/authStore';
import { useChatStore } from '@/stores/chatStore';
import { Settings, Users } from 'lucide-react';
import { useState, type FC } from 'react';
import { useParams } from 'react-router-dom';
import { ChatRoomSettingsDialog } from './ChatRoomSettingsDialog';
import { Badge } from './ui/badge';
import { Button } from './ui/button';

export const NavBar: FC = () => {
  const { chatRooms, onlineUsers } = useChatStore();
  const { roomId } = useParams<{ roomId: string }>();
  const [isSettingsOpen, setIsSettingsOpen] = useState(false);
  const { user } = useAuthStore();
  const currentRoom = chatRooms.find((room) => room.id === roomId);

  const getOnlineMembersCount = () => {
    if (!currentRoom) return 0;
    return currentRoom.members.filter((member) =>
      onlineUsers.has(member.userId)
    ).length;
  };

  return (
    <div className="p-4 border-b border-gray-200 bg-gray-50 flex items-center justify-between dark:bg-gray-800 dark:border-gray-700">
      <div>
        {currentRoom ? (
          <div className="flex flex-col">
            <div className="flex items-center gap-2">
              <h1 className="text-lg font-semibold dark:text-white">
                {currentRoom.name}
              </h1>
              <Badge variant="secondary" className="text-xs">
                <Users className="h-3 w-3 mr-1" />
                {getOnlineMembersCount()} / {currentRoom.members.length} online
              </Badge>
            </div>
            {currentRoom.description && (
              <p className="text-sm text-gray-500 dark:text-gray-300">
                {currentRoom.description}
              </p>
            )}
          </div>
        ) : (
          <h1 className="text-lg font-semibold dark:text-white">Chat App</h1>
        )}
      </div>
      <div>
        {currentRoom &&
          currentRoom.members.some(
            (member) => member.userId === user?.id && member.role === 'admin'
          ) && (
            <Button
              size="sm"
              variant="ghost"
              onClick={() => setIsSettingsOpen(true)}
            >
              <Settings className="h-4 w-4" />
            </Button>
          )}
      </div>

      {currentRoom && (
        <ChatRoomSettingsDialog
          open={isSettingsOpen}
          onOpenChange={setIsSettingsOpen}
          room={currentRoom}
        />
      )}
    </div>
  );
};
