import React, { ComponentProps, ComponentType } from 'react'
import PartnerContentHeader from '../PartnerContentHeader'
import type { ArticleQuery } from '@financial-times/cp-content-pipeline-client'

type Content = ArticleQuery['content']
type HeaderSlotProps = {
  content: Content
}
type HeaderConfig<TProps> = {
  Component: ComponentType<TProps>
  getProps: (content: Content) => TProps
}
type HeaderSlotType = keyof typeof headerConfigs

const isHeaderSlotType = (value: string): value is HeaderSlotType =>
  value in headerConfigs

/**
 * add new configs for new components to this map.
 * They take the format:
 * 'headerSlotTypeFromAPIData': {
 *  Component: YourNewImportedComponent,
 *  getProps: (content) => ({props: props})
 * } satisfies HeaderConfig<ComponentProps<typeof YourNewImportedComponent>>,
 * Also remember to import the component at the top of this file
 */
const headerConfigs = {
  'partner-content': {
    Component: PartnerContentHeader,
    getProps: (content: Content) => ({
      name: ('clientName' in content && content.clientName) || 'Sponsor',
      disclaimerType:
        content.__typename === 'Article' ? content.disclaimerType : undefined,
    }),
  } satisfies HeaderConfig<ComponentProps<typeof PartnerContentHeader>>,
}

/*
 * Factory component to render specialised components to the slot above the main topper area. Full instructions in packages/schema/src/model/strategies/topper/README.md
 */
const HeaderSlot: React.FC<HeaderSlotProps> = ({ content }) => {
  const headerSlotType = content?.topper?.headerSlot?.type
  if (!headerSlotType || !isHeaderSlotType(headerSlotType)) return null

  const { Component, getProps } = headerConfigs[headerSlotType]

  return <Component {...getProps(content)} />
}

export default HeaderSlot
