import React, { useState, useEffect, useMemo, useCallback } from 'react';
import useAsync from 'react-use/lib/useAsync';
import snakeCase from 'lodash/snakeCase';
import { ResponseErrorPanel, Table } from '@backstage/core-components';
import { useApi } from '@backstage/core-plugin-api';
import { optimizationsApiRef } from '../../apis.esm.js';
import { IndexPageLayout } from './private/IndexPageLayout.esm.js';
import { TableToolbar } from './private/table-toolbar/TableToolbar.esm.js';
import { Filters } from './private/filters/Filters.esm.js';
import { BasePage } from '../private/BasePage.esm.js';
import { useTableColumns } from './private/hooks/useTableColumns.esm.js';
import { DEFAULT_DEBOUNCE_INTERVAL, DEFAULT_PADDING, DEFAULT_PAGE_SIZE_OPTIONS, DEFAULT_SORTING_COLUMN, DEFAULT_SORTING_DIRECTION } from './private/defaults.esm.js';

const initialQueryState = {
  limit: DEFAULT_PAGE_SIZE_OPTIONS[0],
  offset: 0,
  orderBy: DEFAULT_SORTING_COLUMN,
  orderHow: DEFAULT_SORTING_DIRECTION
};
const availableFilteringOptionsInitialState = {
  cluster: [],
  project: [],
  workload: [],
  workloadType: []
};
function ResourceOptimizationIndexPage() {
  const [currentPage, setCurrentPage] = useState(0);
  const [availableFilteringOptions, setAvailableFilteringOptions] = useState(availableFilteringOptionsInitialState);
  const [queryState, setQueryState] = useState(initialQueryState);
  const api = useApi(optimizationsApiRef);
  const { value, error, loading } = useAsync(async () => {
    const response = await api.getRecommendationList({ query: queryState });
    return response.json();
  }, [queryState]);
  useEffect(() => {
    const uniqueClusterOptions = /* @__PURE__ */ new Set();
    const uniqueProjectOptions = /* @__PURE__ */ new Set();
    const uniqueWorkloadOptions = /* @__PURE__ */ new Set();
    const uniqueWorkloadTypeOptions = /* @__PURE__ */ new Set();
    for (const {
      clusterAlias,
      project,
      workload,
      workloadType
    } of value?.data ?? []) {
      if (clusterAlias) {
        uniqueClusterOptions.add(clusterAlias);
      }
      if (project) {
        uniqueProjectOptions.add(project);
      }
      if (workload) {
        uniqueWorkloadOptions.add(workload);
      }
      if (workloadType) {
        uniqueWorkloadTypeOptions.add(workloadType);
      }
    }
    const nextAvailableFilteringOptions = {
      cluster: Array.from(uniqueClusterOptions),
      project: Array.from(uniqueProjectOptions),
      workload: Array.from(uniqueWorkloadOptions),
      workloadType: Array.from(uniqueWorkloadTypeOptions)
    };
    setAvailableFilteringOptions(nextAvailableFilteringOptions);
  }, [value?.data]);
  const columns = useTableColumns();
  const optimizableContainersCount = useMemo(
    () => value?.meta?.count ?? 0,
    [value?.meta?.count]
  );
  const data = useMemo(() => value?.data ?? [], [value?.data]);
  const handlePageChange = useCallback(
    (pageNumber, pageSize) => {
      setCurrentPage(pageNumber);
      setQueryState((lastQueryState) => ({
        ...lastQueryState,
        offset: pageNumber * pageSize,
        limit: pageSize
      }));
    },
    []
  );
  const handleRowsPerPageChange = useCallback((pageSize) => {
    setQueryState((lastState) => ({
      ...lastState,
      offset: (lastState.offset ?? 0) * pageSize,
      limit: pageSize
    }));
  }, []);
  const handleOrderChange = useCallback(
    (orderBy, orderDirection) => {
      const { field } = columns[orderBy];
      setQueryState((lastState) => ({
        ...lastState,
        orderBy: field === "clusterAlias" ? "cluster" : snakeCase(field),
        orderHow: orderDirection
      }));
    },
    [columns]
  );
  const handleFiltersChange = useCallback(
    (fieldId, values) => {
      setQueryState((lastQueryState) => ({
        ...lastQueryState,
        offset: 0,
        [fieldId]: values
      }));
      setCurrentPage(0);
    },
    []
  );
  const handleFiltersReset = useCallback(() => {
    if (queryState.cluster?.length === 0 && queryState.project?.length === 0 && queryState.workload?.length === 0 && queryState.workloadType?.length === 0) {
      return;
    }
    setQueryState((lastQueryState) => ({
      ...lastQueryState,
      ...availableFilteringOptionsInitialState
    }));
  }, [
    queryState.cluster?.length,
    queryState.project?.length,
    queryState.workload?.length,
    queryState.workloadType?.length
  ]);
  const handleSearchChange = useCallback((searchText) => {
    setQueryState((lastState) => ({
      ...lastState,
      container: Array.from(new Set(searchText.split(",").filter(Boolean)))
    }));
  }, []);
  if (error) {
    return /* @__PURE__ */ React.createElement(ResponseErrorPanel, { error });
  }
  return /* @__PURE__ */ React.createElement(BasePage, { pageTitle: "Resource Optimization" }, /* @__PURE__ */ React.createElement(IndexPageLayout, null, /* @__PURE__ */ React.createElement(IndexPageLayout.Filters, null, /* @__PURE__ */ React.createElement(
    Filters,
    {
      cluster: {
        options: availableFilteringOptions.cluster ?? [],
        label: "CLUSTERS"
      },
      project: {
        options: availableFilteringOptions.project ?? [],
        label: "PROJECTS"
      },
      workload: {
        options: availableFilteringOptions.workload ?? [],
        label: "WORKLOADS"
      },
      workloadType: {
        options: availableFilteringOptions.workloadType ?? [],
        label: "TYPES"
      },
      onFiltersChange: handleFiltersChange,
      onFiltersReset: handleFiltersReset
    }
  )), /* @__PURE__ */ React.createElement(IndexPageLayout.Table, null, /* @__PURE__ */ React.createElement(
    Table,
    {
      components: {
        Toolbar: TableToolbar
      },
      title: `Optimizable containers (${optimizableContainersCount ?? "N/A"})`,
      options: {
        debounceInterval: DEFAULT_DEBOUNCE_INTERVAL,
        padding: DEFAULT_PADDING,
        pageSize: queryState.limit,
        pageSizeOptions: DEFAULT_PAGE_SIZE_OPTIONS,
        paging: true,
        search: true,
        sorting: true,
        thirdSortClick: false
      },
      data,
      columns,
      isLoading: loading,
      totalCount: optimizableContainersCount,
      page: currentPage,
      onPageChange: handlePageChange,
      onRowsPerPageChange: handleRowsPerPageChange,
      onOrderChange: handleOrderChange,
      onSearchChange: handleSearchChange
    }
  ))));
}

export { ResourceOptimizationIndexPage };
//# sourceMappingURL=ResourceOptimizationIndexPage.esm.js.map
