import type { ColumnDef, Row, Table } from '@tanstack/react-table';
import type { EditableTableProps, TDataWithGroupId } from '../types';
import EditableTableCell from '../editable-table-cell';
import { Spinner } from '../../spinner';
import GroupedRowHeader from '../grouped-row-header/grouped-row-header';
import { Fragment } from 'react/jsx-runtime';

export interface GroupedEditableTableBodyProps<TData> {
  isLoading: boolean;
  columns: ColumnDef<TData>[];
  table: Table<TData>;
  isCellDisabled?: EditableTableProps<TData>['isCellDisabled'];
}
export default function GroupedEditableTableBody<TData>({
  isLoading,
  columns,
  table,
  isCellDisabled,
}: GroupedEditableTableBodyProps<TData>) {
  return (
    <>
      {isLoading ? (
        <tbody>
          <tr className="h-[300px]">
            <td colSpan={columns.length}>
              <div className="flex flex-col items-center justify-center gap-1">
                <Spinner className="h-8 w-8 animate-spin" />
                <p className="pt-1 text-neutral-700">Loading...</p>
              </div>
            </td>
          </tr>
        </tbody>
      ) : table.getRowModel().rows?.length ? (
        // Normal rows
        Object.values(
          table.getRowModel().rows.reduce(
            (acc, item) => {
              (acc[(item.original as TDataWithGroupId<TData>).editableTableGroupId] ??= []).push(
                item,
              );
              return acc;
            },
            {} as Record<string, Row<TData>[]>,
          ),
        ).map((row) => {
          const groupId = (row[0].original as TDataWithGroupId<TData>)?.editableTableGroupId;

          return (
            <Fragment key={groupId}>
              <tbody>
                <GroupedRowHeader groupId={groupId} />
                {row.map((item) => (
                  <tr key={item.id}>
                    {item.getVisibleCells().map((cell) => {
                      return (
                        <EditableTableCell
                          key={`${cell.column.getIndex()}-${cell.row.index}`}
                          cell={cell}
                          isCellDisabled={isCellDisabled}
                        />
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </Fragment>
          );
        })
      ) : (
        // Empty state
        <tbody>
          <tr className="h-[300px]">
            <td colSpan={columns.length}>
              <div className="flex flex-col items-center justify-center gap-1">
                <p role="alert" aria-live="polite" className="text-neutral-700">
                  No data
                </p>
              </div>
            </td>
          </tr>
        </tbody>
      )}
    </>
  );
}
