import { QueryClientProvider, useQuery } from '@tanstack/react-query'
import { StatusChip } from '@overdeck/deck-ui'
import { useState } from 'react'
import { fetchCollectorState } from '../../lib/collector-client'
import { healthChipLabel, healthSummary } from '../../lib/health'
import { createOverdeckQueryClient } from '../../lib/query-client'

function HealthStatusChipContent() {
  const stateQuery = useQuery({
    queryKey: ['collector-state', 'shell-health'],
    queryFn: fetchCollectorState,
    refetchInterval: 30_000,
  })
  const summary = healthSummary(
    stateQuery.data?.adapters,
    stateQuery.isError ? (stateQuery.error instanceof Error ? stateQuery.error.message : 'request failed') : null,
  )
  return (
    <a
      href="/health"
      aria-label={`System health: ${summary.status}. ${summary.detail}`}
      title={summary.detail}
      className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent"
    >
      <StatusChip status={summary.status} label={healthChipLabel(summary)} />
    </a>
  )
}

export function HealthStatusChip() {
  const [queryClient] = useState(createOverdeckQueryClient)
  return (
    <QueryClientProvider client={queryClient}>
      <HealthStatusChipContent />
    </QueryClientProvider>
  )
}
