"use client"

import { useQuery } from "convex/react"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { SlaAtRiskCard } from "@/components/dashboard/dashboard-hero"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"

type AwaitingAction = {
  total: number
  atRisk: number
}

export function DashboardSlaRiskPanel() {
  const { session, convexUserId, isStaff } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const enabled = Boolean(isStaff && convexUserId)

  const overview = useQuery(
    api.reports.dashboardOverview,
    enabled ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as { awaitingAction?: AwaitingAction } | undefined

  return (
    <SlaAtRiskCard
      data={overview?.awaitingAction}
      isLoading={enabled && overview === undefined}
    />
  )
}

