import type { User } from "@/services/auth"
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar"
import { useSocket } from "@/contexts/SocketContext"
import NumberFlow from '@number-flow/react'
import { useEffect, useState } from "react"

interface NavPlanProps {
  user: User
}

export function NavPlan({ user }: NavPlanProps) {
  const [credits, setCredits] = useState(0)
  const { socket, isConnected } = useSocket()
  
  useEffect(() => {
    setCredits(user.credits)
  }, [user])

  // Listen for real-time credits updates
  useEffect(() => {
    if (!socket || !isConnected) return

    const handleCreditsChanged = (data: { credits: number }) => {
      setCredits(data.credits)
    }

    socket.on("credits_changed", handleCreditsChanged)

    // Cleanup listener on unmount
    return () => {
      socket.off("credits_changed", handleCreditsChanged)
    }
  }, [socket, isConnected])

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <SidebarMenuButton
          size="lg"
          className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
        >
          <div className="grid flex-1 text-left text-sm leading-tight">
            <span className="truncate font-semibold">
              Plan: {user.plan.name}
            </span>
            <span className="truncate text-xs">
              Credits: <NumberFlow value={credits} />
            </span>
          </div>
        </SidebarMenuButton>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}