import React, {
  ForwardRefExoticComponent,
  HTMLAttributes,
  ReactElement,
  forwardRef,
} from 'react';
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;
  }>;
}

export const TableSectionRow = forwardRef<
  HTMLTableRowElement,
  TableSectionRowProps<any, any>
>(({ state, RegularTrElement, rowData, ...props }, ref) => {
  const { children, className, style } = props;
  const isSectionRow = state.isSectionRow(rowData);
  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 sectionWithCount = state.getSectionWithCount(rowData);

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

    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' }}
        >
          <CollectionSectionHeader
            section={sectionWithCount}
            biComponentType="TableSections"
            skin="neutral"
            dataHook="table-section-header"
          />
        </th>
      </tr>
    );
  }

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