import { flexRender } from "@tanstack/react-table"
import type { JSX } from "react"
import { useCallback } from "react"
import { TableCell } from "../Table"

interface TableCellProps {
  cell: any
  cellClassName?: string | ((cell: any) => string)
  getWidthStyle: (column: any) => React.CSSProperties
}

export function TableCellComponent({
  cell,
  cellClassName,
  getWidthStyle,
}: TableCellProps): JSX.Element {
  const cellCls = typeof cellClassName === "function" ? cellClassName(cell) : cellClassName

  const renderCellContent = useCallback(() => {
    try {
      return flexRender(cell.column.columnDef.cell, cell.getContext()) as React.ReactNode
    } catch (error) {
      console.warn("Error rendering cell content:", error)
      return cell.getValue() ?? ""
    }
  }, [cell])

  return (
    <TableCell key={cell.id} className={cellCls} style={getWidthStyle(cell.column)}>
      {renderCellContent()}
    </TableCell>
  )
}
