import { useState } from 'react';
import DataTable from 'react-data-table-component';

// Define the Table component as a generic component
interface TableProps<T> {
  columns: {
    name: string;
    selector: (row: T) => string | number;
    sortable: boolean;
  }[];
  data: T[];
}

const Table = <T extends Record<string, any>>({
  columns,
  data,
}: TableProps<T>) => {
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [sortColumn, setSortColumn] = useState<string>('');

  const handleSort = (selectedColumn: any, sortDirection: 'asc' | 'desc') => {
    setSortColumn(selectedColumn.selector);
    setSortDirection(sortDirection);
  };

  const sortedData = [...data].sort((a, b) => {
    const aValue = sortColumn
      ? columns.find((col) => col.name === sortColumn)?.selector(a)
      : a;
    const bValue = sortColumn
      ? columns.find((col) => col.name === sortColumn)?.selector(b)
      : b;

    if (sortDirection === 'asc') {
      if (aValue === undefined || bValue === undefined) {
        return 0;
      }
      return aValue > bValue ? 1 : -1;
    } else {
      if (aValue === undefined || bValue === undefined) {
        return 0;
      }
      return aValue < bValue ? 1 : -1;
    }
  });

  return (
    <>
      <div>
        <DataTable
          columns={columns}
          data={sortedData}
          onSort={handleSort}
          sortServer={false} // Local sorting
          sortIcon={
            <img src="/images/icons/sorting-arrows.png" className="ms-1" />
          }
          className="data-table"
          // @ts-ignore
          direction={sortDirection} // Using 'asc' | 'desc' directly here
        />
      </div>
    </>
  );
};

export default Table;
