import { TableCell as MuiTableCell, Link, Typography } from '@mui/material'
import ReactMarkdown, { type Components } from 'react-markdown'
import type { TableColumn, TableRow } from '../types'
import { getCellValue } from '../helpers'
import type { ReactNode } from 'react'

/**
 * Props for Cell component
 */
export interface CellProps {
  /** Column definition */
  column: TableColumn
  /** Full table row for context */
  row: TableRow
  /** Cell value */
  value: unknown
}

const DEFAULT_P = ({ children }: { children?: ReactNode }) => (
  <Typography component='span' variant='body2' color='inherit'>
    {children}
  </Typography>
)

/**
 * Markdown components for cell content
 * Uses compact styling suitable for table cells (reusing Note widget pattern)
 */
const CELL_MARKDOWN_COMPONENTS: Components = {
  h1: DEFAULT_P,
  h2: DEFAULT_P,
  h3: DEFAULT_P,
  p: DEFAULT_P,
  a: ({ children, href }) => {
    const isExternal = href?.startsWith('http')
    return (
      <Link
        href={href}
        target={isExternal ? '_blank' : undefined}
        rel={isExternal ? 'noopener noreferrer' : undefined}
        color='text.primary'
        underline='always'
      >
        {children}
      </Link>
    )
  },
  img: () => null,
  ul: DEFAULT_P,
  ol: DEFAULT_P,
  li: DEFAULT_P,
}

/**
 * Table cell component with automatic markdown support for string values
 * Markdown is rendered when the raw value is a string and no formatter is defined.
 * If a formatter is used, its output is rendered directly without markdown parsing.
 */
export function Cell({ column, row, value }: CellProps) {
  // If formatter is defined, use it directly without markdown
  if (column.formatter) {
    return (
      <MuiTableCell align={column.align}>
        {column.formatter(value, row)}
      </MuiTableCell>
    )
  }

  // For string values without formatter, render as markdown
  if (typeof value === 'string') {
    return (
      <MuiTableCell align={column.align}>
        <ReactMarkdown components={CELL_MARKDOWN_COMPONENTS}>
          {value}
        </ReactMarkdown>
      </MuiTableCell>
    )
  }

  // For non-string values, render directly
  return <MuiTableCell align={column.align}>{getCellValue(value)}</MuiTableCell>
}
