'use strict';
'use client';
import { c } from 'react/compiler-runtime';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import { createContext, useState, use, useEffect, Children } from 'react';
import { layoutSlots, isResourceListDropdownMenuVisible, shouldDisplayFilterList, isFilterListOrientationVertical, shouldDisplayCardList, getResourceListTableId, getLayoutItemKey } from './ResourceList.funcs.js';
import { Button } from '../../fd-component-toolbox/button/Button.js';
import { tableDisplayModes } from '../../../fd-toolbox/enums/enums.js';
import { cn } from '../../../fd-toolbox/lib/utils.js';
import { ResourceListHeader } from './resource-list-header/ResourceListHeader.js';
import { Table } from '../table/Table.js';
import { CardList } from '../card-list/CardList.js';
import { useResourceListState, useResourceListEffects, useResourceListFilterCallbacks, useRefreshResources, useResourcePaginationAndNavigation } from './resource-list-hooks.js';
import { useRouter, useSearchParams } from '../client/framework/hooks.js';
import { onRestoreState } from './resource-list-persist-state.js';
import { useResourceListConfig } from './use-resource-list-config.js';
import { ResourceFilterList } from '../filtering/resource-filter-list/ResourceFilterList.js';
import { getCustomLayoutItems, getSlotClassName } from '../client/layout.js';
import { BackButton } from '../../fd-component-toolbox/back-button/BackButton.js';
import { ResourceListDropdownMenu } from './resource-list-dropdown-menu/ResourceListDropdownMenu.js';
import { fetchUiResourceMeta } from '../ui-meta-providers.js';
import { useAsyncEffect } from '../../../fd-toolbox/hooks/use-async-effect.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
});
const ResourceListContext = createContext(void 0);
function ResourceList(t0) {
  const $ = c(13);
  const {
    config: resourceListConfigProp,
    resources,
    parentContextName
  } = t0;
  const [uiResourceMeta, setUiResourceMeta] = useState(void 0);
  let t1;
  let t2;
  if ($[0] !== resourceListConfigProp.resourceName) {
    t1 = async () => {
      const fetchedUiResourceMeta = await fetchUiResourceMeta(resourceListConfigProp.resourceName);
      setUiResourceMeta(fetchedUiResourceMeta);
    };
    t2 = [resourceListConfigProp.resourceName];
    $[0] = resourceListConfigProp.resourceName;
    $[1] = t1;
    $[2] = t2;
  } else {
    t1 = $[1];
    t2 = $[2];
  }
  useAsyncEffect(t1, t2);
  const router = useRouter();
  const localSortingPagingFiltering = !(resources instanceof Promise);
  const searchParams = Object.fromEntries(useSearchParams().entries());
  const resourcesProp = localSortingPagingFiltering ? resources : use(resources);
  const tableComponentRef = useEmptyRef();
  const globalResourceListConfig = useResourceListConfig(resourceListConfigProp.resourceName, resourceListConfigProp);
  const customLayoutItems = getCustomLayoutItems([layoutSlots.tableOrCardList, layoutSlots.resourceFilterList], resourceListConfigProp.unstableLayout?.items);
  const {
    state
  } = useResourceListState(resourceListConfigProp.tableRequired ?? true, globalResourceListConfig, resourceListConfigProp.resourceName, uiResourceMeta);
  let t3;
  if ($[3] !== resourceListConfigProp.resourceName || $[4] !== state || $[5] !== uiResourceMeta?.resourceMeta) {
    t3 = () => {
      state.setResourceMeta(uiResourceMeta?.resourceMeta ?? void 0);
      onRestoreState(ResourceList.displayName + resourceListConfigProp.resourceName, state.setComponentState, resourceListConfigProp.resourceName, state.setLoading);
    };
    $[3] = resourceListConfigProp.resourceName;
    $[4] = state;
    $[5] = uiResourceMeta?.resourceMeta;
    $[6] = t3;
  } else {
    t3 = $[6];
  }
  let t4;
  if ($[7] !== resourceListConfigProp.resourceName || $[8] !== state.setComponentState || $[9] !== state.setLoading || $[10] !== state.setResourceMeta || $[11] !== uiResourceMeta) {
    t4 = [resourceListConfigProp.resourceName, state.setLoading, state.setResourceMeta, state.setComponentState, uiResourceMeta];
    $[7] = resourceListConfigProp.resourceName;
    $[8] = state.setComponentState;
    $[9] = state.setLoading;
    $[10] = state.setResourceMeta;
    $[11] = uiResourceMeta;
    $[12] = t4;
  } else {
    t4 = $[12];
  }
  useEffect(t3, t4);
  useResourceListEffects(state, searchParams, localSortingPagingFiltering, resourceListConfigProp.showFilters, globalResourceListConfig, resourceListConfigProp.resourceName, resourcesProp, uiResourceMeta);
  const {
    onFilterChangeCallback,
    onSortCallback,
    isCreateOnlyResourceState
  } = useResourceListFilterCallbacks(state, resourcesProp, resourceListConfigProp.resourceName, localSortingPagingFiltering);
  const {
    refreshResources
  } = useRefreshResources(state, resourcesProp, localSortingPagingFiltering);
  const {
    onPagingCallback,
    onNavigateToResource
  } = useResourcePaginationAndNavigation(state, resourcesProp, localSortingPagingFiltering);
  const contextValue = {
    tableComponentRef,
    refreshResources
  };
  const resourceListId = useElementId(ResourceList.displayName, parentContextName ?? resourceListConfigProp.resourceName);
  return jsxs(ResourceListContext.Provider, {
    value: contextValue,
    children: [state.hasNeededAccess && jsxs("div", {
      className: cn("grid grid-cols-1 gap-4", resourceListConfigProp.unstableLayout?.className),
      children: [!state.loading && jsx("div", {
        className: cn(isFilterListOrientationVertical(state.resourceListConfig) && "flex-col= flex w-full max-w-full", getSlotClassName(layoutSlots.resourceFilterList, resourceListConfigProp.unstableLayout?.items)),
        children: jsxs("div", {
          className: "mt-1 flex w-full flex-row items-start gap-2 pr-2",
          children: [!resourceListConfigProp.hideBackButton && jsxs(Fragment, {
            children: [jsx(BackButton, {
              className: "size-7 shrink-0",
              onClick: () => router.back()
            }), !resourceListConfigProp.hideResourceListDropdownMenu && isResourceListDropdownMenuVisible(true, state.setViewMode) && jsx(ResourceListDropdownMenu, {
              onViewModeChanged: state.setViewMode,
              viewMode: state.viewMode
            })]
          }), shouldDisplayFilterList(resourceListConfigProp.showFilters ?? true, state.resourceMeta, localSortingPagingFiltering) && jsx("div", {
            className: cn("flex w-full flex-row items-center md:p-0", isFilterListOrientationVertical(state.resourceListConfig) && "h-full max-h-full"),
            children: jsx(ResourceFilterList, {
              ref: state.resourceFilterListComponentRef,
              uiResourceMeta,
              stateKey: `${ResourceFilterList.displayName}_${state.resourceMeta.id}_resourceList`,
              onFilterChange: onFilterChangeCallback,
              queryODataFilters: state.queryODataFilters,
              onRefreshResources: refreshResources,
              config: state.resourceListConfig.resourceFilterListConfig,
              parentContextName: resourceListId
            })
          })]
        })
      }), jsxs("div", {
        className: cn("m-0 flex p-0", state.shouldDisplayTable ? "flex-col" : "items-start", isFilterListOrientationVertical(state.resourceListConfig) && "max-h-full w-full overflow-x-auto", getSlotClassName(layoutSlots.tableOrCardList, resourceListConfigProp.unstableLayout?.items)),
        children: [jsx(ResourceListHeader, {
          resourceName: state.resourceName,
          uiResourceMeta: state.uiResourceMeta,
          resourceListEmpty: state.resourcesState.length === 0,
          tableRequired: resourceListConfigProp.tableRequired === false,
          pluralName: resourceListConfigProp.pluralName,
          onRefreshResources: refreshResources
        }), shouldDisplayCardList(state.viewMode) && jsx(CardList, {
          onRefreshItems: refreshResources,
          resources: state.resourcesState,
          uiResourceMeta: state.uiResourceMeta,
          onItemDelete: refreshResources
        }), state.shouldDisplayTable && jsx("div", {
          className: "w-full overflow-auto px-0",
          children: jsx("div", {
            children: jsx(Table, {
              id: getResourceListTableId(state.resourceName),
              ref: tableComponentRef,
              items: state.resourcesState,
              uiResourceMeta: uiResourceMeta ?? state.uiResourceMeta,
              tableConfig: {
                ...state.resourceListConfig.tableConfig,
                readonly: state.readonly,
                externalSorting: true,
                sort: state.componentState.tableSort,
                displayMode: resourceListConfigProp.tableConfig?.displayMode ?? tableDisplayModes.default,
                className: cn(isFilterListOrientationVertical(state.resourceListConfig) && "max-h-full w-full min-w-min overflow-hidden pt-4 pl-2")
              },
              onSort: onSortCallback,
              onPaging: onPagingCallback,
              onRefreshItems: refreshResources,
              onItemDeleted: refreshResources,
              loading: state.loading
            })
          })
        })]
      }), customLayoutItems.map(_temp)]
    }), isCreateOnlyResourceState && jsx(Button, {
      onClick: onNavigateToResource,
      children: "Add"
    })]
  });
}
function _temp(layoutItem) {
  return jsx("div", {
    className: cn(layoutItem.className),
    children: Children.toArray(layoutItem.elements)
  }, getLayoutItemKey(layoutItem));
}
__name(ResourceList, "ResourceList");
ResourceList.displayName = elements.resourceList.resourceListId;

export { ResourceList, ResourceListContext };
