'use strict';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useRef, useImperativeHandle, useEffect } from 'react';
import { tableDisplayModes } from '../../../fd-toolbox/enums/enums.js';
import { getHeight, setTableConfig, createInternalTableColumns, initializeTable, onTableSort, onPagingChange, onMouseLeave, onMouseEnter } from './Table.funcs.js';
import { cn } from '../../../fd-toolbox/lib/utils.js';
import { useAsyncEffect } from '../../../fd-toolbox/hooks/use-async-effect.js';
import { TableBody as tableBodyMemo } from './body/TableBody.js';
import { TableHeader } from './header/TableHeader.js';
import { Pager } from './pager/Pager.js';
import { targetColumnWidthPx, minColumnWidthPx, additionalColumnWidthRem, symbolWidthRem, minColumnWidthPercentage } from './table-constants.js';
import { useMediaQuery } from '../../../fd-toolbox/hooks/use-media-query.js';
import { TableReactContext } from './table-context.js';
import { processLocalRowDeletion } from './services/fd-table-private-rows.js';
import { tableElementSuffixes } from '../../fd-component-toolbox/constants/table-element-suffixes.js';
import { calculateSizing } from '../../fd-component-toolbox/sizing/sizing.js';
import { useEmptyRef } from '../../../fd-toolbox/hooks/use-empty-ref.js';
import { useElementId } from '../../../fd-toolbox/hooks/use-element-id.js';
import { elements } from '../../../fd-toolbox/constants/elements.js';

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", {
  value,
  configurable: true
});
function Table({
  id: idProp,
  tableConfig,
  uiResourceMeta,
  items,
  onSort,
  onPaging,
  onRefreshItems,
  onItemDeleted,
  onRowClick,
  onRowsUpdate,
  loading,
  dataInfo,
  ref
}) {
  const instanceId = useElementId(elements.table.tableElementId);
  const instanceNumber = parseInt(instanceId.split("-").pop() ?? "0", 10);
  const [internalTableColumns, setInternalTableColumns] = useState([]);
  const [tableRows, setTableRows] = useState([]);
  const [tableId, setTableId] = useState(idProp ?? tableElementSuffixes.table + instanceNumber);
  const effectiveDisplayMode = tableConfig.displayMode ?? tableDisplayModes.default;
  const [pageSize, setPageSize] = useState(tableConfig.pageSize ?? 50);
  const fdTableRef = useEmptyRef();
  const possibleColumnValues = useRef(/* @__PURE__ */new Map()).current;
  const [isHovered, setIsHovered] = useState(false);
  const [isActive, setIsActive] = useState(false);
  const [pageNumber, setPageNumber] = useState(1);
  const [columnWidths, setColumnWidths] = useState([]);
  const targetWidth = internalTableColumns.length * targetColumnWidthPx;
  const minWidth = internalTableColumns.length * minColumnWidthPx;
  const isSmallScreen = useMediaQuery(`(max-width: calc(${targetWidth / 16}rem + 10vw))`);
  const tableHeight = pageSize - tableRows.length < 25 && getHeight(pageSize);
  const deleteRowsLocally = /* @__PURE__ */__name(itemIds => setTableRows(prevRows => processLocalRowDeletion(prevRows, itemIds, onRowsUpdate)), "deleteRowsLocally");
  useImperativeHandle(ref, () => ({
    // Approved temp
    // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
    getSelectedRows: /* @__PURE__ */__name(() => tableRows.filter(r => r.selected), "getSelectedRows"),
    getSelectedRowsIds: /* @__PURE__ */__name(() => tableRows.filter(r_0 => r_0.selected).map(selectedRow => selectedRow.item.id), "getSelectedRowsIds"),
    resetSelectedRows: /* @__PURE__ */__name(() => {
      setTableRows(tableRows.map(r_1 => ({
        ...r_1,
        selected: false
      })));
    }, "resetSelectedRows"),
    deleteRowsLocally
  }), [tableRows, deleteRowsLocally]);
  useEffect(() => {
    setTableConfig(setInternalTableColumns, setColumnWidths);
  }, []);
  const effectiveExclude = tableConfig.excludeProperties ?? [];
  useAsyncEffect(() => {
    createInternalTableColumns(setInternalTableColumns, tableConfig, tableConfig.readonly ?? false, effectiveExclude, possibleColumnValues, effectiveDisplayMode, uiResourceMeta, fdTableRef?.current?.getBoundingClientRect().width, [], dataInfo);
    return initializeTable(setInternalTableColumns, tableConfig, tableConfig.readonly ?? false, effectiveExclude, possibleColumnValues, effectiveDisplayMode, instanceNumber, setTableId, tableId, setTableRows, tableRows, internalTableColumns, setPageNumber, fdTableRef?.current, tableConfig.sort, onSort, tableConfig.externalSorting, uiResourceMeta, dataInfo);
  }, [uiResourceMeta, setTableId, tableId]);
  useEffect(() => {
    setTableRows(items.slice(0, pageSize).map((item, index) => ({
      selected: false,
      item,
      index
    })));
  }, [setTableRows, items, pageSize]);
  useEffect(() => {
    setPageSize(tableConfig.pageSize ?? 50);
  }, [tableConfig.pageSize]);
  const resourceDescriptionProperty = uiResourceMeta?.resourceMeta.description.resourceDescriptionProperty;
  let dataDescription;
  if (resourceDescriptionProperty) {
    dataDescription = {
      descriptionPropertyName: resourceDescriptionProperty,
      useImage: uiResourceMeta.resourceMeta.description.useImage
    };
  } else {
    dataDescription = dataInfo?.dataDescription;
  }
  const tableInstance = {
    id: tableId,
    name: uiResourceMeta?.resourceMeta.resourceName ?? dataInfo?.name,
    tableRows,
    internalTableColumns,
    uiResourceMeta,
    getColumnPossibleValues: /* @__PURE__ */__name(str => possibleColumnValues.get(str), "getColumnPossibleValues"),
    customActions: tableConfig?.customActions,
    multiSelect: tableConfig.multiSelect,
    disableCellNavigationLinks: tableConfig.disableCellNavigationLinks,
    dataDescription
  };
  const [columnToWidthPercent, setColumnToWidthPercent] = useState({});
  const [containerStyle, setContainerStyle] = useState({});
  useEffect(() => {
    const result = calculateSizing(internalTableColumns, 0, {
      columnOptions: {
        minPercentage: minColumnWidthPercentage,
        symbolWidth: symbolWidthRem,
        additionalWidth: additionalColumnWidthRem,
        minPixels: minColumnWidthPx
      },
      isSmallScreen,
      minWidthPx: minWidth,
      targetWidthPx: targetWidth,
      adaptiveWidth: tableConfig.adaptiveWidth
    });
    setColumnToWidthPercent(result.columnPercents ?? {});
    setContainerStyle(result.containerStyles ?? {});
  }, [internalTableColumns, isSmallScreen, minWidth, targetWidth, tableConfig.adaptiveWidth]);
  const tableContextValue = {
    columnWidths,
    setColumnWidths,
    tableRows,
    setTableRows,
    loading: loading ?? false
  };
  return /* @__PURE__ */jsx(TableReactContext.Provider, {
    value: tableContextValue,
    children: /* @__PURE__ */jsxs("div", {
      role: "table",
      className: cn("relative flex size-full flex-col justify-between overflow-visible", tableConfig.className),
      style: containerStyle,
      onMouseEnter: () => onMouseEnter(effectiveDisplayMode, setIsHovered),
      onMouseLeave: () => onMouseLeave(effectiveDisplayMode, setIsHovered),
      children: [/* @__PURE__ */jsxs("div", {
        className: "flex flex-col",
        children: [internalTableColumns.length > 0 && /* @__PURE__ */jsx("div", {
          className: "border-muted flex flex-col justify-start border-b",
          children: /* @__PURE__ */jsx(TableHeader, {
            tableInstance,
            tableSorted: column => onTableSort(column, internalTableColumns, tableRows, updatedRows => setTableRows([...updatedRows]), onSort, tableConfig.externalSorting),
            onRefreshItems,
            displayMode: effectiveDisplayMode,
            tableHovered: isHovered,
            columnToWidthPercent
          })
        }), /* @__PURE__ */jsx("div", {
          id: tableId,
          ref: fdTableRef,
          className: `h-full ${tableHeight}`,
          children: internalTableColumns.length > 0 && /* @__PURE__ */jsx("div", {
            className: "flex flex-col justify-start",
            children: /* @__PURE__ */jsx(tableBodyMemo, {
              tableInstance,
              onRefreshItems,
              deleteItem: onItemDeleted,
              onRowClick,
              rowHighlightBehavior: tableConfig.rowHighlightBehavior,
              tableActionType: effectiveDisplayMode
            })
          })
        })]
      }), /* @__PURE__ */jsx("div", {
        className: cn(!isHovered && !isActive && effectiveDisplayMode === tableDisplayModes.minimal && "invisible"),
        children: /* @__PURE__ */jsx(Pager, {
          displayMode: effectiveDisplayMode,
          pageSize,
          rowCount: tableRows.length,
          onPaging: paging => onPagingChange(paging, setPageSize, onPaging),
          setIsActive,
          setPageNumber,
          pageNumber
        })
      })]
    })
  });
}
__name(Table, "Table");
Table.displayName = elements.table.tableElementId;

export { Table };
