import React from 'react'

import { type TooltipContentProps } from './ChartTooltipTypes'
import styles from './_charts-tooltip.module.scss'
import { c } from '../../../translations/LibraryTranslationService'

const TooltipBodyContent: React.FC<TooltipContentProps> = ({
  data,
  config,
  hasColumnHeader,
  rowTotalData,
  type = 'default',
}) => {
  const cellStyles = `${styles.cellWrap} ${hasColumnHeader ? styles.cellWrapTable : ''}`

  return (
    <table className={styles.tooltipBodycontentContainer}>
      {hasColumnHeader ? (
        <thead className={styles.tableHeadContainer}>
          <tr>
            {config.map((column) => (
              // column.name is the unique key for the table column headers
              <th key={column.name}>
                <div className={styles.tableCellHeaderWrap}>{column.label}</div>
              </th>
            ))}
          </tr>
        </thead>
      ) : null}
      <tbody>
        {data.map((row, rowIndex) => (
          <tr key={rowIndex}>
            {config.map((column, columnIndex) => (
              <td key={columnIndex} className={cellStyles}>
                <div className={styles.primaryColumnWrap}>
                  {(type === 'swatchLine' ||
                    (type === 'table' && row?.swatchLineColor)) &&
                  columnIndex === 0 ? (
                    <div
                      className={`${styles.swatchLineBar} ${!hasColumnHeader ? styles.extraMarginBottom : ''}`}
                      style={{
                        backgroundColor: `var(--${row.swatchLineColor})`,
                      }}
                    />
                  ) : (
                    <></>
                  )}
                  <div>{row[column.name]}</div>
                </div>
              </td>
            ))}
          </tr>
        ))}

        {/* TODO: Move the 'total' row logic to a separate component. */}
        {/* Not all variants of the table have a 'total' row */}
        {rowTotalData ? (
          <tr className={styles.totalRowWrap}>
            <td className={cellStyles}>{c('total')}</td>
            {config.slice(1).map((column, columnIndex) => (
              <td key={columnIndex} className={cellStyles}>
                {rowTotalData[column.name]}
              </td>
            ))}
          </tr>
        ) : null}
      </tbody>
    </table>
  )
}

export default TooltipBodyContent
