import React, {
  Children,
  MutableRefObject,
  ReactElement,
  ReactNode,
} from 'react';
import { NestedTableGhostIndentationCell } from './NestedTableGhostIndentationCell';
import { FiltersMap } from '@wix/bex-core';
import { NestedTableDataItem } from '../../state/NestedTableState/NestedTableNodeState';
import { classes, st } from './NestedTableDragAndDropRow.st.css.js';
import { observer } from 'mobx-react-lite';

export interface NestedTableDragAndDropRowProps<
  C extends string,
  T,
  F extends FiltersMap,
> {
  item: NestedTableDataItem<C, T, F>;
  children: ReactElement<{
    children: ReactNode;
    className?: string;
  }>;
  forwardedRef:
    | ((instance: HTMLTableRowElement | null) => void)
    | MutableRefObject<HTMLTableRowElement | null>
    | null;
}

function _NestedTableDragAndDropRow<C extends string, T, F extends FiltersMap>(
  props: NestedTableDragAndDropRowProps<C, T, F>,
) {
  const { children, item, forwardedRef } = props;
  const { type: Tr, key, props: trProps } = children;

  const { nestedTable } = item.state;
  const nestedTableDragAndDrop = nestedTable.nestedTableDragAndDrop!;

  const { dragEventParentAndAfter } = nestedTableDragAndDrop;

  const node = dragEventParentAndAfter?.node;

  return (
    <Tr
      key={key}
      ref={forwardedRef}
      {...trProps}
      className={st(
        classes.root,
        {
          draggingInto:
            node?.parent?.id === item.originalKeyedItem.id &&
            !node.node._expanded,
        },
        trProps.className,
      )}
    >
      <NestedTableGhostIndentationCell item={item} />
      {Children.toArray(trProps.children)}
    </Tr>
  );
}

export const NestedTableDragAndDropRow = observer(_NestedTableDragAndDropRow);
