import type { SkeletonLoaderProps } from './types'
import { useWidgetSelector } from '../stores/use-widget-selector'
import { Suspense } from 'react'

/**
 * Displays a skeleton loading placeholder while widget data is loading. Subscribes to widget loading state in the store and renders the provided Skeleton component or children accordingly.
 *
 * @example
 * ```tsx
 * <SkeletonLoader id="sales-chart" Skeleton={BarSkeleton}>
 *   <Bar id="sales-chart" />
 * </SkeletonLoader>
 * ```
 */
export function SkeletonLoader({
  id,
  children,
  Skeleton,
}: SkeletonLoaderProps) {
  const isLoading = useWidgetSelector(id, (w) => w?.isLoading)

  if (isLoading) {
    if (!Skeleton) {
      return null
    }

    return (
      <Suspense fallback={null}>
        <Skeleton />
      </Suspense>
    )
  }

  return children
}
