import { useQuery } from '@tanstack/react-query'
import { CheckCircle2, XCircle, Clock, CalendarDays, CalendarRange, Timer } from 'lucide-react'
import { getDashboardStats } from '../../../api/dashboard'

function Skeleton() {
  return (
    <div className="animate-pulse space-y-2">
      {[0, 1, 2, 3].map((i) => (
        <div key={i} className="h-12 rounded-lg bg-surface-muted" />
      ))}
    </div>
  )
}

function formatTime(seconds: number | null): string {
  if (seconds == null) return '--'
  if (seconds < 60) return `${seconds.toFixed(1)}s`
  const m = Math.floor(seconds / 60)
  const s = Math.round(seconds % 60)
  return `${m}m ${s}s`
}

export default function RenderThroughputWidget() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: getDashboardStats,
    staleTime: 30_000,
    retry: 1,
  })

  if (isLoading) return <Skeleton />
  if (error) return <p className="text-xs text-red-500">Failed to load render throughput</p>
  if (!data) return null

  const t = data.render_throughput

  const periods = [
    { label: 'Today', completed: t.completed_today, failed: t.failed_today, icon: <Clock size={14} className="text-blue-500" /> },
    { label: 'This Week', completed: t.completed_this_week, failed: t.failed_this_week, icon: <CalendarDays size={14} className="text-indigo-500" /> },
    { label: 'This Month', completed: t.completed_this_month, failed: t.failed_this_month, icon: <CalendarRange size={14} className="text-purple-500" /> },
  ]

  return (
    <div className="space-y-2">
      {periods.map(({ label, completed, failed, icon }) => (
        <div
          key={label}
          className="flex items-center justify-between rounded-lg border border-border-default p-3"
          style={{ backgroundColor: 'var(--color-bg-surface)' }}
        >
          <div className="flex items-center gap-2">
            {icon}
            <span className="text-sm text-content-secondary">{label}</span>
          </div>
          <div className="flex items-center gap-3">
            <span className="flex items-center gap-1 text-sm font-semibold text-green-600">
              <CheckCircle2 size={13} />
              {completed}
            </span>
            {failed > 0 && (
              <span className="flex items-center gap-1 text-sm font-semibold text-red-500">
                <XCircle size={13} />
                {failed}
              </span>
            )}
          </div>
        </div>
      ))}

      {/* Render time stats */}
      <div
        className="flex items-center justify-between rounded-lg border border-border-default p-3"
        style={{ backgroundColor: 'var(--color-bg-surface)' }}
      >
        <div className="flex items-center gap-2">
          <Timer size={14} className="text-amber-500" />
          <span className="text-sm text-content-secondary">Avg / Median</span>
        </div>
        <span className="text-sm font-semibold text-content">
          {formatTime(t.avg_render_time_s)} / {formatTime(t.median_render_time_s)}
        </span>
      </div>
    </div>
  )
}
