import {
  Header,
  flexRender,
  Updater,
  ColumnOrderState,
  TableState,
  Column,
} from '@tanstack/react-table';
import classNames from 'classnames';
import {FC} from 'react';
import css from '../index.module.css';
import {useDrag, useDrop} from 'react-dnd';
import {arrayMove} from '@dnd-kit/sortable';

type Props = {
  update: (updater: Updater<ColumnOrderState>) => void;
  header: Header<Record<string, any>, unknown>;
  getState: () => TableState;
};

const HeaderTh: FC<Props> = function ({header, update, getState}) {
  const [, dropRef] = useDrop({
    accept: 'table',
    drop(item: Column<any>) {
      const {id: fromId} = item,
        toId = header.column.id;

      if (fromId === toId) return;
      const {columnOrder} = getState();

      const fromIdx = columnOrder.findIndex(val => val === fromId),
        toIdx = columnOrder.findIndex(val => val === toId);

      update(arrayMove(columnOrder, fromIdx, toIdx));
    },
  });

  const [_, dragRef] = useDrag({
    type: 'table',
    item: () => header.column,
    collect(monitor) {
      return {isDragging: monitor.isDragging()};
    },
  });

  return (
    <th
      key={header.id}
      style={{
        width: header.getSize(),
        cursor: 'pointer',
      }}
      ref={dropRef}
    >
      <div ref={dragRef}>
        {header.isPlaceholder
          ? null
          : flexRender(header.column.columnDef.header, header.getContext())}

        <div
          onMouseDown={header.getResizeHandler()}
          onClick={e => e.stopPropagation()}
          className={classNames(css.resizer, {
            [css.resizing]: header.column.getIsResizing(),
          })}
        />
      </div>
    </th>
  );
};

export default HeaderTh;
