import {useSortable} from '@dnd-kit/sortable';
import {Row, flexRender} from '@tanstack/react-table';
import classNames from 'classnames';
import {CSSProperties, FC, ReactNode} from 'react';

type Props = {
  highlight?: boolean,
  enableDnd?: boolean,
  preview?: boolean,
  row: Row<Record<string, any>>,
  renderSubComponent?: (row: Row<Record<string, any>>) => ReactNode;
  enableEllipsis?: boolean;
};

const BodyTr: FC<Props> = function({
  row,
  highlight,
  enableDnd,
  preview,
  renderSubComponent,
  enableEllipsis,
}) {
  const trList = row.getVisibleCells();
  const {setNodeRef, listeners, attributes} = useSortable({
    id: row.id,
    disabled: !enableDnd,
    data: {
      row,
    },
  });

  return (
    <>
      <tr
        ref={setNodeRef}
        {...listeners}
        {...attributes}
        style={{cursor: enableDnd || preview ? 'move' : 'auto'}}
        className={classNames('ld-table-body-tr ', {
          'ld-table-tr-highlight': highlight,
          'ld-table-tr-preview': preview,
        })}
      >
        {trList.map(function({
          id,
          column,
          getContext,
        }) {
          const {
            align,
            fixed,
            fixedStyle,
            ellipsis,
          } = column.columnDef.meta as {
            align?: 'left' | 'center' | 'right';
            fixed?: 'right' | 'left';
            fixedStyle: CSSProperties,
            ellipsis?: boolean,
          };

          return (
            <td
              title={getContext().getValue() as string}
              key={id}
              className={classNames({
                'ld-table-fixed-right ld-table-right-fixed-shadow': fixed === 'right',
                'ld-table-fixed-left ld-table-left-fixed-shadow': fixed === 'left',
                'ld-table-ellipsis': !fixed && ((enableEllipsis && ellipsis !== false) || ellipsis),
              })}
              style={{
                width: column.getSize(),
                textAlign: align ?? 'left',
                ...fixedStyle,
              }}
            >
              {flexRender(
                column.columnDef.cell,
                getContext(),
              )}
            </td>
          );
        })}
      </tr>

      {row.getIsExpanded() && Boolean(renderSubComponent)
        ? (
          <tr className="ld-table-body-tr">
            <td colSpan={row.getVisibleCells().length}>
              {renderSubComponent?.(row)}
            </td>
          </tr>
        )
        : null}
    </>
  );
};

export default BodyTr;
