"use client"

import { useMemo } from "react"
import { useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import {
  MachineDetails,
  normalizeMachineItem,
  type MachinesQueryItem,
} from "@/components/admin/machines/admin-machines-overview"
import { Card, CardContent } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import type { Id } from "@/convex/_generated/dataModel"

export function AdminMachineDetailsClient({ tenantId, machineId }: { tenantId: string; machineId: string }) {
  const single = useQuery(
    (api as any).machines.getById,
    machineId ? ({ id: machineId as Id<"machines">, includeMetadata: true } as const) : ("skip" as const)
  ) as
    | Record<string, unknown>
    | null
    | undefined
  const machine: MachinesQueryItem | null = useMemo(() => {
    if (single === undefined || single === null) return single as null
    return normalizeMachineItem(single)
  }, [single])
  const isLoading = single === undefined

  if (isLoading) {
    return (
      <Card>
        <CardContent className="space-y-3 p-6">
          <Skeleton className="h-6 w-64" />
          <Skeleton className="h-4 w-80" />
          <Skeleton className="h-48 w-full" />
        </CardContent>
      </Card>
    )
  }

  return <MachineDetails machine={machine} />
}
