"use client"

import { useEffect, useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { useParams, useRouter } from "next/navigation"
import { api } from "@/convex/_generated/api"
import {
  DeviceDetails,
  normalizeDeviceItem,
  type DevicesQueryItem,
} from "@/components/admin/devices/admin-devices-overview"
import { Card, CardContent } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
import { Button } from "@/components/ui/button"
import type { Id } from "@/convex/_generated/dataModel"
import { ConvexHttpClient } from "convex/browser"

export function AdminDeviceDetailsClient({ tenantId: _tenantId, deviceId }: { tenantId: string; deviceId?: string }) {
  const router = useRouter()
  const params = useParams<{ id?: string | string[] }>()
  const routeDeviceId = Array.isArray(params?.id) ? params?.id[0] : params?.id
  const effectiveDeviceId = deviceId ?? routeDeviceId ?? ""

  const canLoadDevice = Boolean(effectiveDeviceId)

  const single = useQuery(
    api.devices.getById,
    canLoadDevice
      ? ({ id: effectiveDeviceId as Id<"machines">, includeMetadata: true } as const)
      : "skip"
  )

  // Fallback via HTTP in caso de o Convex React demorar/ficar preso em loading
  const [fallback, setFallback] = useState<Record<string, unknown> | null | undefined>(undefined)
  const [loadError, setLoadError] = useState<string | null>(null)
  const [retryTick, setRetryTick] = useState(0)
  const shouldLoad = fallback === undefined && Boolean(effectiveDeviceId)
  const [isHydrated, setIsHydrated] = useState(false)

  useEffect(() => {
    setIsHydrated(true)
  }, [])

  useEffect(() => {
    if (!shouldLoad) return
    let cancelled = false

    const probe = async () => {
      try {
        const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL
        if (convexUrl) {
          try {
            const http = new ConvexHttpClient(convexUrl)
            const data = (await http.query(api.devices.getById, {
              id: effectiveDeviceId as Id<"machines">,
              includeMetadata: true,
            })) as Record<string, unknown> | null

            if (cancelled) return

            if (data) {
              setFallback(data)
              setLoadError(null)
              return
            }

            if (data === null) {
              setFallback(null)
              setLoadError(null)
              return
            }
          } catch (err) {
            if (cancelled) return
          }
        }

        try {
          const res = await fetch(`/api/admin/devices/${effectiveDeviceId}/details`, {
            credentials: "include",
            cache: "no-store",
          })

          if (cancelled) return

          let payload: Record<string, unknown> | null = null
          try {
            payload = (await res.json()) as Record<string, unknown> | null
          } catch {
            payload = null
          }

          if (res.ok) {
            setFallback(payload ?? null)
            setLoadError(null)
            return
          }

          const message =
            typeof payload?.error === "string" && payload.error
              ? payload.error
              : `Falha ao carregar (HTTP ${res.status})`

          if (res.status === 404) {
            setFallback(null)
            setLoadError(null)
          } else {
            setLoadError(message)
          }
        } catch (err) {
          if (!cancelled) {
            console.error("[admin-device-details] API fallback fetch failed", err)
            setLoadError("Erro de rede ao carregar os dados da dispositivo.")
          }
        }
      } catch (err) {
        if (!cancelled) {
          console.error("[admin-device-details] Unexpected probe failure", err)
          setLoadError("Erro de rede ao carregar os dados da dispositivo.")
        }
      }
    }

    probe().catch((err) => {
      if (!cancelled) {
        console.error("[admin-device-details] Probe promise rejected", err)
        setLoadError("Erro de rede ao carregar os dados da dispositivo.")
      }
    })

    return () => {
      cancelled = true
    }
  }, [shouldLoad, effectiveDeviceId, retryTick])

  // Timeout de proteção: se depois de X segundos ainda estiver carregando e sem fallback, mostra erro claro
  useEffect(() => {
    if (!shouldLoad) return
    const timeout = setTimeout(() => {
      setLoadError((error) =>
        error ?? "Tempo esgotado ao consultar os dados (Convex). Verifique sua conexão e tente novamente."
      )
    }, 10_000)
    return () => clearTimeout(timeout)
  }, [shouldLoad, effectiveDeviceId, retryTick])

  const device: DevicesQueryItem | null = useMemo(() => {
    const source = single ?? (fallback === undefined ? undefined : fallback)
    if (source === undefined || source === null) return source as null
    return normalizeDeviceItem(source)
  }, [single, fallback])
  const isLoading = single === undefined && fallback === undefined && !loadError
  const isNotFound = (single === null || fallback === null) && !loadError

  if (!isHydrated) {
    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>
    )
  }

  const onRetry = () => {
    setLoadError(null)
    setFallback(undefined)
    setRetryTick((t) => t + 1)
    // força revalidação de RSC/convex subscription
    try {
      router.refresh()
    } catch {
      // ignore
    }
  }
  if (loadError && !device) {
    return (
      <Card>
        <CardContent className="space-y-3 p-6">
          <p className="text-sm font-medium text-red-600">Falha ao carregar os dados da dispositivo</p>
          <p className="text-sm text-muted-foreground">{loadError}</p>
          <div className="pt-2 flex items-center gap-2">
            <Button size="sm" onClick={onRetry}>Tentar novamente</Button>
          </div>
        </CardContent>
      </Card>
    )
  }

  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>
    )
  }

  if (isNotFound) {
    return (
      <Card>
        <CardContent className="space-y-3 p-6">
          <p className="text-sm font-medium text-red-600">Dispositivo não encontrada</p>
          <p className="text-sm text-muted-foreground">Verifique o identificador e tente novamente.</p>
          <div className="pt-2 flex items-center gap-2">
            <Button size="sm" onClick={onRetry}>Recarregar</Button>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <DeviceDetails device={device} />
}
