import React, {
  ForwardRefExoticComponent,
  HTMLAttributes,
  ReactElement,
  forwardRef,
} from 'react';
import { observer } from 'mobx-react-lite';
import { FiltersMap, KeyedItem } from '@wix/bex-core';
import { TableSectionsState } from './TableSectionsState';
import { CollectionSectionHeader } from '../CollectionSectionHeader';

export interface TableSectionRowProps<T, F extends FiltersMap>
  extends HTMLAttributes<HTMLTableRowElement> {
  rowData: KeyedItem<T>;
  state: TableSectionsState<T, F>;
  RegularTrElement: ForwardRefExoticComponent<{
    children: ReactElement[];
    rowData: { id: string };
    className: string;
  }>;
}

const _TableSectionRow = forwardRef<
  HTMLTableRowElement,
  TableSectionRowProps<any, any>
>(({ state, RegularTrElement, rowData, ...props }, ref) => {
  const { children, className, style } = props;
  const isSectionRow = state.isSectionRow(rowData);
  const contentWidth = state.table.toolbar.itemsContentRect.rect.width;
  const sectionContentWidth = contentWidth ? `${contentWidth}px` : '100%';
  const regularTrElementProps = {
    ...props,
    rowData,
    className: className || '',
    children: (children as ReactElement[]) || [],
  };

  if (state.isInvisibleRow(rowData)) {
    return (
      <tr
        {...props}
        ref={ref}
        className={className}
        style={{
          ...style,
          visibility: 'collapse',
        }}
      />
    );
  }

  if (isSectionRow && Array.isArray(children) && children.length > 0) {
    const result = state.getSectionWithCount(rowData);

    if (!result) {
      return <RegularTrElement {...regularTrElementProps} />;
    }

    const { sectionId, sectionIndex, section, collapsible } = result;

    return (
      <tr
        {...props}
        ref={ref}
        className={className}
        style={{
          ...style,
          position: 'relative',
          cursor: 'default',
        }}
        data-hook="table-section-header-row"
      >
        <th
          colSpan={children.length}
          scope="rowgroup"
          style={{ padding: '0px' }}
        >
          <div
            style={{
              position: 'sticky',
              left: 0,
              width: sectionContentWidth,
            }}
          >
            <CollectionSectionHeader
              sectionId={sectionId}
              sectionIndex={sectionIndex}
              section={section}
              biComponentType="TableSections"
              skin="neutral"
              dataHook="table-section-header"
              collapsible={collapsible}
              onToggleCollapse={state.toggleSection}
            />
          </div>
        </th>
      </tr>
    );
  }

  return <RegularTrElement {...regularTrElementProps} />;
});

export const TableSectionRow = observer(_TableSectionRow);
