import { u as useMultiQuery, a as useTheme, b as usePartsOfUrl, c as useAutoPerRequestError, m as mergePerRequestErrors, p as parseAll, d as usePermissions, s as serializeLabelsWithNoEncoding, _, j as jp, e as useDirectUnknownResource, f as useK8sSmartResource, g as jsxRuntimeExports, P as PerRequestError, R as ReadOnlyModal, E as EnrichedTableProvider, D as DeleteIcon, h as EditIcon, i as PaddingContainer, k as getLinkToForm, l as DeleteModal, n as DeleteModalMany } from './index-cNF5QCwf.mjs';
import { useState } from 'react';
import { useLocation, useParams, useNavigate } from 'react-router-dom';
import { theme, Flex, Spin, Button } from 'antd';
import { PlusOutlined, ClearOutlined, MinusOutlined } from '@ant-design/icons';
import '@tanstack/react-query';
import 'novnc-next';
import styled from 'styled-components';

const ColorContainer = styled.div`
  color: ${({ $colorText }) => $colorText};

  & tr,
  td {
    color: ${({ $colorText }) => $colorText};
  }
`;
const Styled = {
  ColorContainer
};

const EnrichedTableModal = ({
  open,
  onClose,
  modalTitle,
  modalDescriptionText,
  modalDescriptionTextStyle,
  editModalWidth,
  fetchUrl,
  k8sResourceToFetch,
  pathToItems,
  additionalReqsDataToEachItem,
  cluster,
  labelSelector,
  labelSelectorFull,
  fieldSelector,
  namespace,
  k8sResource,
  dataForControls,
  baseprefix,
  pathToKey,
  ...props
}) => {
  const location = useLocation();
  const params = useParams();
  const navigate = useNavigate();
  const { token } = theme.useToken();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRowsData, setSelectedRowsData] = useState([]);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [isDeleteModalManyOpen, setIsDeleteModalManyOpen] = useState(
    false
  );
  const { data: multiQueryData, isLoading: isMultiqueryLoading, hasErrorForReq } = useMultiQuery();
  const theme$1 = useTheme();
  const partsOfUrl = usePartsOfUrl();
  const allProps = {
    fetchUrl,
    k8sResourceToFetch,
    pathToItems,
    additionalReqsDataToEachItem,
    cluster,
    labelSelector,
    labelSelectorFull,
    fieldSelector,
    namespace,
    k8sResource,
    dataForControls,
    baseprefix,
    pathToKey,
    modalTitle,
    modalDescriptionText,
    ...props
  };
  const autoErrorResult = useAutoPerRequestError(allProps);
  const { shouldShowError, errorToShow } = mergePerRequestErrors(autoErrorResult, hasErrorForReq, [
    labelSelectorFull?.reqIndex,
    ...additionalReqsDataToEachItem ?? []
  ]);
  const replaceValues = partsOfUrl.partsOfUrl.reduce((acc, value, index) => {
    acc[index.toString()] = value;
    return acc;
  }, {});
  const clusterPrepared = parseAll({ text: cluster, replaceValues, multiQueryData });
  const namespacePrepared = namespace ? parseAll({ text: namespace, replaceValues, multiQueryData }) : void 0;
  const k8sResourcePrePrepared = k8sResource ? {
    apiGroup: k8sResource.apiGroup ? parseAll({ text: k8sResource.apiGroup, replaceValues, multiQueryData }) : void 0,
    apiVersion: parseAll({ text: k8sResource.apiVersion, replaceValues, multiQueryData }),
    plural: parseAll({ text: k8sResource.plural, replaceValues, multiQueryData })
  } : void 0;
  const k8sResourcePrepared = k8sResourcePrePrepared?.apiGroup === "-" ? { apiVersion: k8sResourcePrePrepared.apiVersion, plural: k8sResourcePrePrepared.plural } : k8sResourcePrePrepared;
  const dataForControlsPrepared = dataForControls ? {
    cluster: clusterPrepared,
    syntheticProject: dataForControls.syntheticProject ? parseAll({ text: dataForControls.syntheticProject, replaceValues, multiQueryData }) : void 0,
    plural: parseAll({ text: dataForControls.plural, replaceValues, multiQueryData }),
    apiGroup: dataForControls.apiGroup ? parseAll({ text: dataForControls.apiGroup, replaceValues, multiQueryData }) : void 0,
    apiVersion: parseAll({ text: dataForControls.apiVersion, replaceValues, multiQueryData })
  } : void 0;
  const createPermission = usePermissions({
    apiGroup: dataForControlsPrepared?.apiGroup,
    plural: dataForControlsPrepared?.plural || "",
    namespace: namespacePrepared,
    cluster: clusterPrepared,
    verb: "create",
    refetchInterval: false,
    enabler: Boolean(dataForControlsPrepared && clusterPrepared && !isMultiqueryLoading)
  });
  const fetchUrlPrepared = fetchUrl ? parseAll({ text: fetchUrl, replaceValues, multiQueryData }) : void 0;
  const k8sResourceToFetchPrepared = k8sResourceToFetch ? {
    apiGroup: k8sResourceToFetch.apiGroup ? parseAll({ text: k8sResourceToFetch.apiGroup, replaceValues, multiQueryData }) : void 0,
    apiVersion: parseAll({ text: k8sResourceToFetch.apiVersion, replaceValues, multiQueryData }),
    plural: parseAll({ text: k8sResourceToFetch.plural, replaceValues, multiQueryData }),
    namespace: k8sResourceToFetch.namespace ? parseAll({ text: k8sResourceToFetch.namespace, replaceValues, multiQueryData }) : void 0
  } : void 0;
  const sParams = new URLSearchParams();
  if (labelSelector && Object.keys(labelSelector).length > 0) {
    const parsedObject = Object.fromEntries(
      Object.entries(labelSelector).map(
        ([k, v]) => [k, parseAll({ text: v, replaceValues, multiQueryData })]
      )
    );
    const serializedLabels = serializeLabelsWithNoEncoding(parsedObject);
    if (serializedLabels.length > 0) sParams.set("labelSelector", serializedLabels);
  }
  if (labelSelectorFull) {
    const root = multiQueryData[`req${labelSelectorFull.reqIndex}`];
    const value = Array.isArray(labelSelectorFull.pathToLabels) ? _.get(root || {}, labelSelectorFull.pathToLabels) : jp.query(root || {}, `$${labelSelectorFull.pathToLabels}`)[0];
    const serializedLabels = serializeLabelsWithNoEncoding(value);
    if (serializedLabels.length > 0) sParams.set("labelSelector", serializedLabels);
  }
  if (fieldSelector) {
    const parsedObject = Object.fromEntries(
      Object.entries(fieldSelector).map(
        ([k, v]) => [
          parseAll({ text: k, replaceValues, multiQueryData }),
          parseAll({ text: v, replaceValues, multiQueryData })
        ]
      )
    );
    const serializedFields = serializeLabelsWithNoEncoding(parsedObject);
    if (serializedFields.length > 0) sParams.set("fieldSelector", serializedFields);
  }
  const searchParams = sParams.toString();
  const {
    data: fetchedData,
    isLoading: isFetchedDataLoading,
    error: fetchedDataError
  } = useDirectUnknownResource({
    uri: `${fetchUrlPrepared}${searchParams ? `?${searchParams}` : ""}`,
    queryKey: [`${fetchUrlPrepared}${searchParams ? `?${searchParams}` : ""}`],
    isEnabled: Boolean(!isMultiqueryLoading && fetchUrlPrepared)
  });
  const {
    data: fetchedDataSocket,
    isLoading: isFetchedDataSocketLoading,
    error: fetchedDataSocketError
  } = useK8sSmartResource({
    cluster: clusterPrepared || "",
    namespace: k8sResourceToFetchPrepared?.namespace,
    apiGroup: k8sResourceToFetchPrepared?.apiGroup,
    apiVersion: k8sResourceToFetchPrepared?.apiVersion || "",
    plural: k8sResourceToFetchPrepared?.plural || "",
    fieldSelector: sParams.get("fieldSelector") || void 0,
    labelSelector: sParams.get("labelSelector") || void 0,
    isEnabled: Boolean(!isMultiqueryLoading && k8sResourceToFetchPrepared)
  });
  if (fetchUrlPrepared && isMultiqueryLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Loading multiquery" });
  }
  if (k8sResourceToFetchPrepared && isMultiqueryLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Loading multiquery" });
  }
  if (shouldShowError) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(PerRequestError, { error: errorToShow });
  }
  if (fetchUrlPrepared && isFetchedDataLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Flex, { justify: "center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Spin, {}) });
  }
  if (k8sResourceToFetchPrepared && isFetchedDataSocketLoading) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(Flex, { justify: "center", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Spin, {}) });
  }
  if (fetchUrlPrepared && fetchedDataError) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      "Error: ",
      JSON.stringify(fetchedDataError)
    ] });
  }
  if (k8sResourceToFetchPrepared && fetchedDataSocketError) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { children: [
      "Error: ",
      JSON.stringify(fetchedDataError)
    ] });
  }
  const dataFromOneOfHooks = fetchedData || fetchedDataSocket || {};
  const items = Array.isArray(pathToItems) ? _.get(dataFromOneOfHooks || {}, pathToItems) : jp.query(dataFromOneOfHooks || {}, `$${pathToItems}`)[0];
  const itemsAlwaysArr = Array.isArray(items) ? items : [];
  let additionalReqsData = [];
  if (additionalReqsDataToEachItem) {
    additionalReqsDataToEachItem.forEach((item) => {
      additionalReqsData?.push(multiQueryData[`req${item}`]);
    });
  }
  additionalReqsData = additionalReqsData.length > 0 ? additionalReqsData : void 0;
  const itemsAlwaysArrWithAdditionalData = itemsAlwaysArr.map((el) => ({
    ...el,
    ...additionalReqsData ? { additionalReqsData } : {}
  }));
  const clearSelected = () => {
    setSelectedRowKeys([]);
    setSelectedRowsData([]);
  };
  const onDeleteHandle = (name, endpoint) => {
    setIsDeleteModalOpen({ name, endpoint });
  };
  const fullPath = `${location.pathname}${location.search}`;
  const modalTitlePrepared = modalTitle ? parseAll({ text: modalTitle, replaceValues, multiQueryData }) : "Edit";
  const modalDescriptionTextPrepared = modalDescriptionText ? parseAll({ text: modalDescriptionText, replaceValues, multiQueryData }) : void 0;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ReadOnlyModal,
      {
        open,
        close: onClose,
        modalTitle: modalTitlePrepared,
        modalDescriptionText: modalDescriptionTextPrepared,
        modalDescriptionTextStyle,
        editModalWidth,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Styled.ColorContainer, { $colorText: token.colorText, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          EnrichedTableProvider,
          {
            tableMappingsReplaceValues: replaceValues,
            cluster: clusterPrepared,
            namespace: namespacePrepared,
            theme: theme$1,
            dataItems: itemsAlwaysArrWithAdditionalData,
            tableProps: {
              borderless: true,
              paginationPosition: ["bottomRight"],
              isTotalLeft: true,
              editIcon: /* @__PURE__ */ jsxRuntimeExports.jsx(EditIcon, {}),
              deleteIcon: /* @__PURE__ */ jsxRuntimeExports.jsx(DeleteIcon, {}),
              disablePagination: true
            },
            selectData: dataForControlsPrepared ? {
              selectedRowKeys,
              onChange: (selectedRowKeys2, selectedRowsData2) => {
                setSelectedRowKeys(selectedRowKeys2);
                setSelectedRowsData(selectedRowsData2);
              }
            } : void 0,
            k8sResource: k8sResourcePrepared,
            dataForControlsInternal: { onDeleteHandle },
            dataForControls: dataForControlsPrepared,
            withoutControls: !dataForControlsPrepared,
            baseprefix,
            pathToKey,
            ...props
          }
        ) })
      }
    ),
    dataForControlsPrepared && /* @__PURE__ */ jsxRuntimeExports.jsx(PaddingContainer, { $padding: "4px", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { justify: "space-between", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Button,
        {
          type: "primary",
          onClick: () => {
            const url = getLinkToForm({
              cluster: clusterPrepared,
              baseprefix,
              namespace: namespacePrepared,
              syntheticProject: params.syntheticProject,
              apiGroup: dataForControlsPrepared.apiGroup,
              apiVersion: dataForControlsPrepared.apiVersion,
              plural: dataForControlsPrepared.plural,
              fullPath
            });
            navigate(url);
          },
          loading: createPermission.isPending,
          disabled: !createPermission.data?.status.allowed,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(PlusOutlined, {}),
            "Add"
          ]
        }
      ),
      selectedRowKeys.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(Flex, { gap: 16, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { type: "primary", onClick: clearSelected, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(ClearOutlined, {}),
          "Clear"
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(Button, { type: "primary", onClick: () => setIsDeleteModalManyOpen(selectedRowsData), children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(MinusOutlined, {}),
          "Delete"
        ] })
      ] })
    ] }) }),
    isDeleteModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
      DeleteModal,
      {
        name: isDeleteModalOpen.name,
        onClose: () => {
          setIsDeleteModalOpen(false);
          clearSelected();
        },
        endpoint: isDeleteModalOpen.endpoint
      }
    ),
    isDeleteModalManyOpen !== false && /* @__PURE__ */ jsxRuntimeExports.jsx(
      DeleteModalMany,
      {
        data: isDeleteModalManyOpen,
        onClose: () => {
          setIsDeleteModalManyOpen(false);
          clearSelected();
        }
      }
    )
  ] });
};

export { EnrichedTableModal };
//# sourceMappingURL=index-Cd_VfUiH.mjs.map
