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

interface MediaItem {
  id: string
  filename: string
  thumbnail_url: string | null
  created_at: string
}

interface MediaListResponse {
  items: MediaItem[]
  total: number
}

function Skeleton() {
  return (
    <div className="grid grid-cols-4 gap-2 animate-pulse">
      {[...Array(8)].map((_, i) => (
        <div key={i} className="aspect-square rounded bg-surface-muted" />
      ))}
    </div>
  )
}

export default function RecentRendersWidget() {
  const { data, isLoading, error } = useQuery<MediaItem[]>({
    queryKey: ['recent-renders-widget'],
    queryFn: async () => {
      try {
        const res = await api.get<MediaListResponse>('/media', {
          params: { limit: 8, sort: '-created_at' },
        })
        return res.data?.items ?? []
      } catch {
        // media endpoint may not be available in all deployments
        return []
      }
    },
    staleTime: 60_000,
    retry: 1,
  })

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

  const items = data ?? []

  if (items.length === 0) {
    return (
      <p className="text-xs text-content-muted text-center py-4">
        No renders yet
      </p>
    )
  }

  return (
    <div className="grid grid-cols-4 gap-2">
      {items.map((item) => (
        <div
          key={item.id}
          className="aspect-square rounded overflow-hidden border border-border-default bg-surface-muted"
          title={item.filename}
        >
          {item.thumbnail_url ? (
            <img
              src={item.thumbnail_url}
              alt={item.filename}
              className="w-full h-full object-cover"
              loading="lazy"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center">
              <span className="text-xs text-content-muted text-center px-1 truncate">
                {item.filename}
              </span>
            </div>
          )}
        </div>
      ))}
    </div>
  )
}
