import { Alert, AlertTitle } from '@mui/material'
import { useWidgetSelector } from '../stores/use-widget-selector'
import type { WidgetErrorProps } from './types'

/**
 * Displays an error alert when a widget encounters an error during data loading. Reads error state from the widget store and hides errors during loading/fetching to prevent flashing.
 *
 * @example
 * ```tsx
 * <WidgetError id="my-widget">
 *   <WidgetContent />
 * </WidgetError>
 * ```
 */
export function WidgetError({
  id,
  children,
  title: titleProp,
  description,
}: WidgetErrorProps) {
  // Single consolidated subscription instead of 3 separate ones.
  const { isLoading, isFetching, error } = useWidgetSelector(id, (w) => ({
    isLoading: w?.isLoading,
    isFetching: w?.isFetching,
    error: w?.error,
  }))

  // Don't show error during loading/fetching states
  if (isLoading || isFetching) {
    return children
  }

  // Show error UI if error exists
  if (error) {
    const errorTitle = titleProp ?? error.title ?? 'Error'
    const errorMessage =
      description ??
      error.message ??
      'An error occurred while loading the widget. Please try again.'

    return (
      <Alert severity='error'>
        <AlertTitle>{errorTitle}</AlertTitle>
        {errorMessage}
      </Alert>
    )
  }

  // No error, render children
  return children
}
