"use client"

import Link from "next/link"
import { useMemo } from "react"
import { useQuery } from "convex/react"
import type { Id } from "@/convex/_generated/dataModel"
import { api } from "@/convex/_generated/api"
import { useAuth } from "@/lib/auth-client"

type BreadcrumbSegment = {
  label: string
  href?: string | null
}

type DeviceBreadcrumbsProps = {
  tenantId: string
  deviceId: string
  deviceHref?: string | null
  extra?: BreadcrumbSegment[]
}

export function DeviceBreadcrumbs({ tenantId: _tenantId, deviceId, deviceHref, extra }: DeviceBreadcrumbsProps) {
  const { convexUserId } = useAuth()
  const canLoadDevice = Boolean(deviceId && convexUserId)
  const item = useQuery(
    api.devices.getById,
    canLoadDevice
      ? ({ id: deviceId as Id<"machines">, includeMetadata: false } as const)
      : "skip"
  )
  const hostname = useMemo(() => item?.hostname ?? "Detalhe", [item])
  const segments = useMemo(() => {
    const trail: BreadcrumbSegment[] = [
      { label: "Dispositivos", href: "/admin/devices" },
      { label: hostname, href: deviceHref ?? undefined },
    ]
    if (Array.isArray(extra) && extra.length > 0) {
      trail.push(...extra.filter((segment): segment is BreadcrumbSegment => Boolean(segment?.label)))
    }
    return trail
  }, [hostname, deviceHref, extra])

  return (
    <nav className="mb-4 text-sm text-neutral-600">
      <ol className="flex items-center gap-2">
        {segments.map((segment, index) => {
          const isLast = index === segments.length - 1
          const content = segment.href && !isLast ? (
            <Link href={segment.href} className="underline-offset-4 hover:underline">
              {segment.label}
            </Link>
          ) : (
            <span className={isLast ? "text-neutral-800" : "text-neutral-600"}>{segment.label}</span>
          )
          return (
            <li key={`${segment.label}-${index}`} className="flex items-center gap-2">
              {content}
              {!isLast ? <span className="text-neutral-400">/</span> : null}
            </li>
          )
        })}
      </ol>
    </nav>
  )
}
