import { MessageCircle } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { useUnreadMessages } from "@/hooks/useUnreadMessages";
import { cn } from "@/lib/utils";

interface Props {
  to: string;
  size?: "sm" | "md";
  className?: string;
}

/**
 * Messages icon with realtime unread badge.
 * Reused across Admin, Board, and Homeowner top nav bars.
 */
export function MessagesIconButton({ to, size = "sm", className }: Props) {
  const navigate = useNavigate();
  const { unreadCount } = useUnreadMessages();

  const dim = size === "sm" ? "h-7 w-7" : "h-8 w-8";
  const iconDim = size === "sm" ? "h-3.5 w-3.5" : "h-4 w-4";

  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className={cn(dim, "relative text-muted-foreground hover:text-foreground", className)}
          onClick={() => navigate(to)}
        >
          <MessageCircle className={iconDim} />
          {unreadCount > 0 && (
            <Badge className="absolute -top-1 -right-1 h-4 min-w-4 px-1 text-[10px] flex items-center justify-center bg-destructive text-destructive-foreground border-0">
              {unreadCount > 9 ? "9+" : unreadCount}
            </Badge>
          )}
        </Button>
      </TooltipTrigger>
      <TooltipContent>Messages{unreadCount > 0 ? ` (${unreadCount} unread)` : ""}</TooltipContent>
    </Tooltip>
  );
}
