import {useContent} from '../../hooks/content/useContent'
import {Content} from '../../types'

import {ContentMonitor} from './content-monitor'

interface BaseContentWrapperProps {
  children: ({
    content,
    loading,
  }: {
    content?: Content
    loading: boolean
  }) => JSX.Element | null
}

interface PublicIdContentWrapperProps extends BaseContentWrapperProps {
  publicId: string
  externalId?: never
}

interface ExternalIdContentWrapperProps extends BaseContentWrapperProps {
  externalId: string
  publicId?: never
}

type ContentWrapperProps =
  | PublicIdContentWrapperProps
  | ExternalIdContentWrapperProps

// It's too messy in the docs to show the complete types here so we show a simplified version
export interface ContentWrapperPropsForDocs extends BaseContentWrapperProps {
  publicId?: string
  externalId?: string
}

export function ContentWrapper({
  publicId,
  externalId,
  children,
}: ContentWrapperProps) {
  const {content, loading} = useContent({
    identifiers: [{publicId, externalId}],
    skip: !publicId && !externalId,
  })

  const contentItem = content?.[0]

  if (loading || !contentItem) {
    return children({loading})
  }

  return (
    <ContentMonitor publicId={contentItem.publicId}>
      {children({content: contentItem, loading})}
    </ContentMonitor>
  )
}
