import { Link, List, ListItem, Typography } from '@mui/material'
import ReactMarkdown, { type Components } from 'react-markdown'
import { styles } from '../markdown/style'
import type { MarkdownComponentProps } from './types'

const COMPONENTS: Components = {
  h1: ({ children }) => (
    <Typography variant='h4' gutterBottom color='inherit'>
      {children}
    </Typography>
  ),
  h2: ({ children }) => (
    <Typography variant='h5' gutterBottom color='inherit'>
      {children}
    </Typography>
  ),
  h3: ({ children }) => (
    <Typography variant='h6' gutterBottom color='inherit'>
      {children}
    </Typography>
  ),
  p: ({ children }) => (
    <Typography paragraph color='inherit'>
      {children}
    </Typography>
  ),
  a: ({ children, href, target = '_blank', rel = 'noopener noreferrer' }) => (
    <Link href={href} target={target} rel={rel}>
      {children}
    </Link>
  ),
  ul: ({ children }) => <List sx={styles.ul}>{children}</List>,
  ol: ({ children }) => (
    <List component='ol' sx={styles.ol}>
      {children}
    </List>
  ),
  li: ({ children }) => <ListItem sx={styles.li}>{children}</ListItem>,
}

/**
 * Presentational component that renders a Markdown string as MUI-styled HTML using react-markdown.
 *
 * @remarks
 * Maps Markdown elements (headings, paragraphs, links, lists) to MUI Typography and Link components.
 * Custom component overrides can be passed via the `overrides` prop.
 */
export function MarkdownUI({ children, overrides }: MarkdownComponentProps) {
  return (
    <ReactMarkdown
      components={{
        ...COMPONENTS,
        ...overrides,
      }}
    >
      {children}
    </ReactMarkdown>
  )
}
