import { useQuery } from '@tanstack/react-query'
import { Cpu } from 'lucide-react'
import api from '../../../api/client'

interface ActivityEntry {
  cad_file_id: string
  original_name: string
  processing_status: string
  created_at: string
  updated_at?: string
}

interface ActivityResponse {
  cad_processing: ActivityEntry[]
  render_jobs: ActivityEntry[]
}

function Skeleton() {
  return (
    <div className="animate-pulse space-y-2">
      <div className="h-8 rounded-lg bg-surface-muted" />
      <div className="h-24 rounded bg-surface-muted" />
    </div>
  )
}

export default function WorkerStatusWidget() {
  const { data, isLoading, error } = useQuery<ActivityResponse>({
    queryKey: ['worker-status-widget'],
    queryFn: async () => {
      const res = await api.get('/worker/activity')
      return res.data as ActivityResponse
    },
    refetchInterval: 15_000,
    staleTime: 10_000,
    retry: 1,
  })

  if (isLoading) return <Skeleton />
  if (error) {
    return <p className="text-xs text-red-500">Failed to load worker status</p>
  }

  const entries = data?.cad_processing ?? []
  const processing = entries.filter((e) => e.processing_status === 'processing')
  const failed = entries.filter((e) => e.processing_status === 'failed')
  const completed = entries.filter((e) => e.processing_status === 'completed')

  const overallStatus =
    processing.length > 0
      ? 'active'
      : failed.length > 0
      ? 'degraded'
      : 'idle'

  const statusColor = {
    active: 'text-blue-600',
    degraded: 'text-red-500',
    idle: 'text-green-600',
  }[overallStatus]

  const dotColor = {
    active: 'bg-blue-500 animate-pulse',
    degraded: 'bg-red-500',
    idle: 'bg-green-500',
  }[overallStatus]

  return (
    <div className="space-y-3">
      {/* Status header */}
      <div className="flex items-center gap-2">
        <span className={`inline-block w-2.5 h-2.5 rounded-full ${dotColor}`} />
        <Cpu size={14} className="text-content-muted" />
        <span className={`text-sm font-semibold capitalize ${statusColor}`}>
          {overallStatus}
        </span>
      </div>

      {/* Counters */}
      <div className="grid grid-cols-3 gap-2 text-center">
        <div
          className="rounded-lg border border-border-default py-2"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <p className="text-lg font-bold text-blue-500">{processing.length}</p>
          <p className="text-xs text-content-muted">Active</p>
        </div>
        <div
          className="rounded-lg border border-border-default py-2"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <p className="text-lg font-bold text-green-500">{completed.length}</p>
          <p className="text-xs text-content-muted">Done</p>
        </div>
        <div
          className="rounded-lg border border-border-default py-2"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <p className={`text-lg font-bold ${failed.length > 0 ? 'text-red-500' : 'text-content-muted'}`}>
            {failed.length}
          </p>
          <p className="text-xs text-content-muted">Failed</p>
        </div>
      </div>

      {/* Last activity timestamp */}
      {entries.length > 0 && (
        <p className="text-xs text-content-muted">
          Last activity:{' '}
          {new Date(entries[0].created_at).toLocaleString('de-DE', {
            day: '2-digit',
            month: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          })}
        </p>
      )}
    </div>
  )
}
