import {Header, flexRender} from '@tanstack/react-table';
import classNames from 'classnames';
import {FC, CSSProperties} from 'react';
import css from '../index.module.css';
import {useSortable} from '@dnd-kit/sortable';

type Props = {
  header: Header<Record<string, any>, unknown>;
  useDiv?: boolean;
};

const HeaderTh: FC<Props> = function ({header, useDiv}) {
  const {setNodeRef, attributes, listeners} = useSortable({
    id: header.id,
    data: {header},
  });

  const style: CSSProperties = {
    width: header.getSize(),
    cursor: 'pointer',
    opacity: useDiv ? '0.5' : '1',
  };

  if (useDiv) {
    return (
      <div
        key={header.id}
        style={style}
        ref={setNodeRef}
        {...attributes}
        {...listeners}
        className={css.tableHeadTh}
      >
        {header.isPlaceholder
          ? null
          : flexRender(header.column.columnDef.header, header.getContext())}

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

  return (
    <th
      key={header.id}
      style={style}
      ref={setNodeRef}
      {...attributes}
      {...listeners}
      className={css.tableHeadTh}
    >
      {flexRender(header.column.columnDef.header, header.getContext())}

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

export default HeaderTh;
