import React from "react";

function renderValue(value) {
  if (value == null) return "";
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  if (Array.isArray(value)) {
    if (!value.length) return "[]";
    return `[${value.length} items]`;
  }
  if (typeof value === "object") {
    return "{...}";
  }
  return String(value);
}

export default function DataTable({
  columns = [],
  rows = [],
  keyField = "id",
  onRowClick,
  emptyMessage = "No records yet.",
  isRowSelected
}) {
  const isEmpty = !rows.length;

  return (
    <div className={`swi-table-wrap${isEmpty ? " swi-table-wrap--empty" : ""}`}>
      <table className="swi-table">
        <thead>
          <tr>
            {columns.map((c) => (
              <th key={c.key}>{c.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {isEmpty ? (
            <tr className="swi-table__empty-row">
              <td colSpan={columns.length || 1}>{emptyMessage}</td>
            </tr>
          ) : (
            rows.map((row, idx) => {
              const selected = Boolean(isRowSelected?.(row));
              return (
                <tr
                  key={row[keyField] ?? idx}
                  className={selected ? "swi-table__row--selected" : undefined}
                  onClick={onRowClick ? () => onRowClick(row) : undefined}
                >
                  {columns.map((c) => (
                    <td key={c.key}>{c.render ? c.render(row) : renderValue(row[c.key])}</td>
                  ))}
                </tr>
              );
            })
          )}
        </tbody>
      </table>
    </div>
  );
}
