import "./style.pcss";
import { Fragment, useMemo } from "react";
import type { IComponent } from "#package/types";
import {
  BlockTableBody,
  BlockTableCaption,
  BlockTableCell,
  BlockTableFoot,
  BlockTableHead,
  BlockTableRow,
  BlockTableSortBtn,
} from "./components";
import type {
  IBlockTable,
  IOnBlockTableRowClickArg,
  TBlockTableItemType,
  IOnBlockTableSortArgs,
  IBlockTableSortBtn,
  IBlockTableCell,
  IBlockTableRow,
} from "./config/types";
import { BlockTableContext } from "./context";
import { getTableItem as getTableItemDefaultFn } from "./utils/getTableItem";
import { useCN } from "../../utils/react/useCN";

/**
 * Компонент адаптивных таблиц
 * @returns
 */
const BlockTable: IComponent<IBlockTable> = ({
  baseClass = "blockTable",
  extraClasses = {},
  extraAttrs = { "data-js-adaptive-table-custom": "" },
  children = null,
  items = [],
  isAutoLabels = true,
  getTableItem = getTableItemDefaultFn,
  formatCell = (cell = {}) => cell,
}) => {

  const { getCN } = useCN(baseClass);

  const value = useMemo(() => ({
    getCN, formatCell, items, isAutoLabels,
  }), [ formatCell, items, isAutoLabels, getCN ]);

  return (
    <BlockTableContext value={value}>
      <table className={getCN("", extraClasses)} {...extraAttrs}>
        {children || items.map((group, index) => {
          const key = `${group?.type ?? "tbody"}_${index.toString()}`;
          return (
            <Fragment key={key}>
              {getTableItem({ ...group, key })}
            </Fragment>
          );
        })}
      </table>
    </BlockTableContext>
  );

};

export type {
  IBlockTable,
  IBlockTableCell,
  IBlockTableRow,
  IBlockTableSortBtn,
  IOnBlockTableRowClickArg,
  IOnBlockTableSortArgs,
  TBlockTableItemType,
};

export {
  BlockTable,
  BlockTableBody,
  BlockTableCaption,
  BlockTableCell,
  BlockTableFoot,
  BlockTableHead,
  BlockTableRow,
  BlockTableSortBtn,
};
