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;
  isSecondLevel?: boolean;
};

const HeaderTh: FC<Props> = function ({header, useDiv, isSecondLevel}) {
  const {fixed, disabledSort} = header.column.columnDef.meta as {
    fixed: boolean;
    disabledSort: boolean;
  };

  const {setNodeRef, attributes, listeners} = useSortable({
    id: header.id,
    data: {header},
    disabled: disabledSort,
  });

  const isResizing = header.column.getIsResizing();

  const style: CSSProperties = {
    width: `${header.getSize()}px !important`,
    cursor: isResizing ? 'col-resize' : disabledSort ? 'auto' : 'move',
    boxShadow: useDiv
      ? '0.5px 0.6px 12.3px rgba(0, 0, 0, 0.059),4px 5px 80px rgba(0, 0, 0, 0.1)'
      : '',
  };

  if (useDiv) {
    return (
      <div
        key={header.id}
        style={{...style, backgroundColor: '#f5f5f5'}}
        ref={setNodeRef}
        {...attributes}
        {...listeners}
        className={classNames(css.tableHeadTh, {
          [css.previewTransform]: isSecondLevel,
        })}
      >
        {header.isPlaceholder
          ? null
          : flexRender(header.column.columnDef.header, header.getContext())}
      </div>
    );
  }

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

      {!fixed ? (
        <div
          onMouseDown={header.getResizeHandler()}
          onPointerDown={e => e.stopPropagation()}
          className={classNames(css.resizer, {
            [css.resizing]: isResizing,
          })}
        />
      ) : null}
    </th>
  );
};

export default HeaderTh;
