import React from 'react';
import _ from 'lodash';

export interface Field {
  key: string;
  label: string;
  transform?: (value: string) => JSX.Element | string;
}

interface Props {
  items?: any[];
  fields: Field[];
  handleRowClick?: (index: number) => void;
}

const getItemField = (item: any, field: Field) => {
  const value = _.get(item, field.key);
  return field.transform ? field.transform(value) : value;
};


const ListTable: React.FC<Props> = ({ items = [], fields, handleRowClick = () => {} }) => {
  if (!items.length) return <div className="text-center p-6">No data</div>;
  return (
    <table className="table-auto w-full">
      <thead>
        <tr className="border-b select-none">
          {fields.map(field => <th className="pl-3 text-left bg-gray-100" key={field.label}>{field.label}</th>)}
        </tr>
      </thead>
      <tbody>
        {items.map((item, index) => (
          <tr
            key={item._id}
            className={`border-b hover:bg-gray-100 cursor-pointer ${index % 2 && 'bg-gray-50'}`}
            onClick={() => handleRowClick(index)}
          >
            {fields.map(field => (
              <td key={`${item._id} ${field.label}`} className="p-3">
                {getItemField(item, field)}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default ListTable;
