import { j as jsxRuntimeExports } from "./jsx-runtime-ClFauRgV.esm.js";
import { styled, Menu as Menu$1, MenuItem, Chip as Chip$1, Box } from "@mui/material";
import { T as Typography, g as generateRouteWithId, u as useAuth } from "./useAuth-CEQTm2rv.esm.js";
import { D as Document } from "./document-DKQMhgnk.esm.js";
import { u as defaultCurrencyFormat, M as formatAmount, aR as toFixedWithNumbers, v as defaultCurrencySymbol, Q as formatDate, W as formatLabel, N as formatAmountWithCurrency } from "./common-B0qL-cCR.esm.js";
import { Link } from "react-router-dom";
import React__default, { useEffect } from "react";
import _ from "lodash";
import { i as images } from "./images-DvZ6-RV8.esm.js";
/* empty css                         */
import dayjs from "dayjs";
import "react-i18next";
import { b as getApiConfigSafe } from "./api-config-GOys-syK.esm.js";
const StyledMenu = styled(Menu$1)(() => ({
  ".MuiPaper-rounded": {
    borderRadius: "0.5rem",
    minWidth: "10rem"
  }
}));
const Menu = ({ children, anchorEl, onClose, open, ...rest }) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    StyledMenu,
    {
      id: "basic-menu",
      anchorEl,
      open,
      onClose,
      MenuListProps: {
        "aria-labelledby": "basic-button"
      },
      ...rest,
      children
    }
  ) });
};
const average = (data, column) => {
  const sum2 = data.reduce(
    (acc, row) => acc + Number(extractNumber(row[column])),
    0
  );
  const count = data.length;
  return !isNaN(sum2) ? `${_.round(sum2 / count, 2)}` : "-";
};
const extractNumber = (inputString) => {
  if (typeof inputString === "string") {
    const match = inputString.match(/[\d,]+(\.\d{1,2})?/);
    return match ? match[0] : 0;
  }
  return inputString;
};
const sum = (data, column) => {
  const sum2 = data.reduce(
    (acc, row) => acc + Number(extractNumber(row[column])),
    0
  );
  return !isNaN(sum2) ? `${_.round(sum2, 2)}` : "-";
};
const max = (data, column) => {
  const maxVal = Math.max(...data.map((row) => Number(row[column])));
  return `${maxVal}`;
};
const countEmpty = (data, column) => {
  const empty = data == null ? void 0 : data.filter(
    (d) => {
      const value = _.get(d, column);
      return isNaN(Number(value)) ? Boolean(!_.size(value)) : Boolean(!Number(value));
    }
  );
  return `${empty.length}`;
};
const percentageEmpty = (data, column) => {
  const empty = data == null ? void 0 : data.filter(
    (d) => {
      const value = _.get(d, column);
      return isNaN(Number(value)) ? Boolean(!_.size(value)) : Boolean(!Number(value));
    }
  );
  const percentage = empty.length / data.length * 100;
  return `${_.round(percentage, 2)}%`;
};
const percentageFull = (data, column) => {
  const full = data == null ? void 0 : data.filter(
    (d) => {
      const value = _.get(d, column);
      return isNaN(Number(value)) ? Boolean(_.size(value)) : Boolean(Number(value));
    }
  );
  const percentage = full.length / data.length * 100;
  return `${_.round(percentage, 2)}%`;
};
const countFull = (data, column) => {
  const full = data == null ? void 0 : data.filter(
    (d) => {
      const value = _.get(d, column);
      return isNaN(Number(value)) ? Boolean(_.size(value)) : Boolean(Number(value));
    }
  );
  return `${full.length}`;
};
const none = () => {
  return null;
};
const min = (data, column) => {
  const minValue = Math.min(...data.map((row) => Number(row[column])));
  return `${minValue}`;
};
const aggregationFns = {
  none,
  min,
  max,
  sum,
  average,
  countEmpty,
  countFull,
  percentageEmpty,
  percentageFull
};
const aggregations = [
  {
    label: "Count Empty",
    value: "count_empty"
  },
  {
    label: "Count Full",
    value: "count_full"
  },
  {
    label: "Percentage Full",
    value: "percentage_full"
  },
  {
    label: "Percentage Empty",
    value: "percentage_empty"
  },
  {
    label: "Average",
    value: "average"
  },
  {
    label: "Sum",
    value: "sum"
  },
  {
    label: "None",
    value: "none"
  }
];
const aggregationFnsLookup = {
  count_empty: aggregationFns.countEmpty,
  count_full: aggregationFns.countFull,
  percentage_empty: aggregationFns.percentageEmpty,
  percentage_full: aggregationFns.percentageFull,
  average: aggregationFns.average,
  sum: aggregationFns.sum,
  none: aggregationFns.none
};
const DefaultAggregation = ({
  data,
  column
  // columnDef
}) => {
  const [selectedType, setSelectedType] = React__default.useState("none");
  const [anchorEl, setAnchorEl] = React__default.useState(null);
  const [calculatedValue, setCalculatedValue] = React__default.useState();
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const handleAggregationType = (val) => {
    setSelectedType(val);
    handleClose();
  };
  useEffect(() => {
    const func = aggregationFnsLookup[selectedType];
    setCalculatedValue(func(data, column));
  }, [selectedType, column, data]);
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Typography,
      {
        onClick: handleClick,
        sx: { cursor: "pointer", width: "100%", height: "100%" },
        type: "s4",
        weight: "normal",
        color: calculatedValue ? "theme.secondary.1000" : "theme.secondary.500",
        children: calculatedValue || "+ Add Calculation"
      }
    ),
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      Menu,
      {
        id: "basic-menu",
        anchorEl,
        open,
        onClose: handleClose,
        children: aggregations == null ? void 0 : aggregations.map((aggr) => /* @__PURE__ */ jsxRuntimeExports.jsx(
          MenuItem,
          {
            selected: selectedType == (aggr == null ? void 0 : aggr.value),
            onClick: () => handleAggregationType(aggr == null ? void 0 : aggr.value),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { color: "theme.secondary.1000", type: "s4", children: aggr == null ? void 0 : aggr.label })
          },
          aggr.value
        ))
      }
    )
  ] });
};
const StyledChip = styled(Chip$1)(
  ({ theme: { palette }, active, type, inActive }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
    return {
      cursor: "pointer",
      fontSize: ".75rem",
      color: (_a = palette.theme) == null ? void 0 : _a.secondary[800],
      borderRadius: type === "rounded" ? "1.5rem" : "0.25rem",
      backgroundColor: (_b = palette.theme) == null ? void 0 : _b.secondary[200],
      ...active && {
        "&.MuiChip-filled": {
          color: (_c = palette.theme) == null ? void 0 : _c.primary[700],
          backgroundColor: (_d = palette.theme) == null ? void 0 : _d.primary[200],
          "&:hover": {
            backgroundColor: (_e = palette.theme) == null ? void 0 : _e.primary[200]
          }
        },
        "&.MuiChip-outlined": {
          color: (_f = palette.theme) == null ? void 0 : _f.primary[800],
          borderColor: (_g = palette.theme) == null ? void 0 : _g.primary[300],
          "&:hover": {
            backgroundColor: (_h = palette.theme) == null ? void 0 : _h.primary[200]
          }
        }
      },
      ...inActive && {
        "&.MuiChip-filled": {
          color: (_i = palette.theme) == null ? void 0 : _i.error[700],
          backgroundColor: (_j = palette.theme) == null ? void 0 : _j.error[200],
          "&:hover": {
            backgroundColor: (_k = palette.theme) == null ? void 0 : _k.error[200]
          }
        },
        "&.MuiChip-outlined": {
          color: (_l = palette.theme) == null ? void 0 : _l.error[800],
          borderColor: (_m = palette.theme) == null ? void 0 : _m.error[300],
          "&:hover": {
            backgroundColor: (_n = palette.theme) == null ? void 0 : _n.error[200]
          }
        }
      },
      "& .MuiChip-icon": {
        marginRight: "0.125rem",
        marginLeft: "0rem",
        color: "inherit"
      },
      "& .MuiChip-deleteIcon": {
        marginLeft: "0.25rem",
        fontSize: ".875rem",
        color: "inherit",
        marginRight: "0rem"
      },
      "&.MuiChip-root": {
        height: "fit-content",
        padding: "0.25rem 0.5rem",
        ".MuiChip-label": {
          padding: "0rem"
        }
      }
    };
  }
);
const Chip = (props) => {
  const {
    label,
    type = "rounded",
    variant = "filled",
    active = false,
    inActive = false,
    ...rest
  } = props;
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    StyledChip,
    {
      label,
      variant,
      active,
      inActive,
      type,
      ...rest
    }
  );
};
const ValueField = (props) => {
  const { label, children, childrenTypoProps } = props;
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { className: "valueField--Container", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { weight: "medium", type: "s3", color: "theme.secondary.1000", children: label }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { weight: "medium", type: "s5", color: "theme.secondary.700", sx: { wordBreak: "break-all", pr: 1 }, ...childrenTypoProps, children })
  ] });
};
const downloadFile = async (urlString, fileName) => {
  try {
    const apiConfig = getApiConfigSafe();
    const s3BucketUrl = (apiConfig == null ? void 0 : apiConfig.s3BucketUrl) || "https://erpforce-dev.s3.eu-west-1.amazonaws.com/";
    const url = urlString.includes("http") ? urlString : s3BucketUrl + urlString;
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to fetch file: ${response.statusText}`);
    }
    const blob = await response.blob();
    const blobUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = blobUrl;
    link.download = fileName || "downloaded-file";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  } catch (error) {
    console.error("Error downloading file:", error);
    throw error;
  }
};
const getFileNamesFromUrlsAsLink = (fileUrls, mode) => {
  const fUrls = fileUrls ? Array.isArray(fileUrls) ? fileUrls : [fileUrls] : [];
  if (fUrls && fUrls.length) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      Box,
      {
        display: "flex",
        gap: 1,
        mb: 1,
        alignItems: "center",
        flexDirection: "column",
        children: fUrls.map((url) => {
          const fileName = url.substring(url.lastIndexOf("/") + 1);
          return /* @__PURE__ */ jsxRuntimeExports.jsx(
            Typography,
            {
              type: "s3",
              weight: "medium",
              color: "#246DFF",
              sx: { textDecoration: "underline", textUnderlineOffset: "3px", cursor: "pointer" },
              noWrap: true,
              onClick: () => mode === "add" ? void 0 : downloadFile(url, fileName),
              children: fileName
            }
          );
        })
      }
    );
  }
  return null;
};
const getFileNamesFromUrls = (fileUrls) => {
  var _a, _b;
  if (!fileUrls) return null;
  if (!((_a = fileUrls == null ? void 0 : fileUrls.filter(Boolean)) == null ? void 0 : _a.length)) return null;
  return (_b = fileUrls == null ? void 0 : fileUrls.filter(Boolean)) == null ? void 0 : _b.map((url) => {
    const fileName = (url == null ? void 0 : url.substring((url == null ? void 0 : url.lastIndexOf("/")) + 1)) || "";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { display: "flex", gap: 1, mb: 1, alignItems: "center", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Document, { fontSize: "small" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Typography,
        {
          type: "s3",
          weight: "medium",
          color: "theme.secondary.1000",
          sx: { cursor: "pointer" },
          noWrap: true,
          onClick: () => downloadFile(url, fileName),
          children: fileName
        }
      )
    ] });
  });
};
const jsonArrayToString = (json) => {
  var _a;
  if (!json) return "";
  try {
    return (_a = JSON.parse(json)) == null ? void 0 : _a.join(", ");
  } catch (error) {
    return "";
  }
};
const getStatusClass = (status) => {
  var _a;
  console.log("🚀 ~ getStatusClass ~ status:", status);
  if (typeof status === "string") {
    const s = (_a = status == null ? void 0 : status.toLowerCase()) == null ? void 0 : _a.replaceAll(" ", "");
    console.log("🚀 ~ getStatusClass ~ s:", s);
    return s;
  } else if (typeof status === "number") {
    return status ? "enabled" : "disabled";
  }
};
const transformTableColumns = ({
  columns = [],
  currencySymbol,
  translationFn = void 0,
  enableFooter = false,
  redirectionLink = "",
  redirectionLinkState = void 0,
  redirectionPathWithId = "",
  idField = "id",
  statusClasses = "",
  rows = [],
  customizeValue = void 0,
  currencyFormat,
  fraction
}) => {
  const currencyFormatData = currencyFormat ? currencyFormat : defaultCurrencyFormat();
  return columns.map((column) => ({
    ...column,
    header: translationFn ? translationFn(column.header) : column.header,
    Cell: ({ renderedCellValue, row }) => {
      var _a, _b, _c, _d;
      let v = renderedCellValue;
      const columnType = column.type || (column.header === "Amount" || column.header === "Rate" ? "currency" : void 0);
      const isAmount = ["currency", "amount"].includes(columnType);
      if (typeof v === "number" && v && ((_a = String(v)) == null ? void 0 : _a.includes("."))) {
        return v = isAmount ? formatAmount(v, currencyFormatData, "before", currencySymbol instanceof Function ? currencySymbol(row) : currencySymbol, fraction) : toFixedWithNumbers(v, fraction);
      }
      switch (columnType) {
        case "formattedString":
          v = formatLabel(renderedCellValue) || "-";
          break;
        case "date":
          v = formatDate(
            renderedCellValue,
            ((_b = column.editProperties) == null ? void 0 : _b.dateFormat) || "DD-MM-YYYY"
          );
          break;
        case "datetime":
          v = formatDate(
            renderedCellValue,
            ((_c = column.editProperties) == null ? void 0 : _c.dateFormat) || "DD-MM-YYYY hh:mm A"
          );
          break;
        case "currency":
        case "amount":
          {
            const cs = (column == null ? void 0 : column.showDefaultCurrency) ? defaultCurrencySymbol() : currencySymbol instanceof Function ? currencySymbol(row) : currencySymbol || defaultCurrencySymbol();
            v = renderedCellValue || renderedCellValue == 0 ? `${formatAmount(renderedCellValue, currencyFormatData, "before", cs, fraction) || "-"}` : null;
          }
          break;
        case "status":
        case "enum":
        case "array":
          {
            v = renderedCellValue || renderedCellValue === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: Array.isArray(renderedCellValue) ? /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: (renderedCellValue == null ? void 0 : renderedCellValue.length) ? /* @__PURE__ */ jsxRuntimeExports.jsx(Box, { sx: { display: "flex", alignItems: "center", gap: 1, flexWrap: "wrap" }, children: renderedCellValue.map((rcv) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              Chip,
              {
                type: "normal",
                className: column.custom_class ? column == null ? void 0 : column.custom_class : typeof rcv === "string" ? rcv : "",
                label: /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight: "medium", color: "inherit", children: typeof rcv === "object" ? _.get(rcv, (column == null ? void 0 : column.typeArrayAccessorKey) || "", "") : rcv })
              }
            )) }) : "-" }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              Chip,
              {
                type: "normal",
                className: column.custom_class ? column == null ? void 0 : column.custom_class : statusClasses instanceof Function ? statusClasses(row) : `${statusClasses}${getStatusClass(renderedCellValue)}`,
                label: /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight: "medium", color: "inherit", children: renderedCellValue })
              }
            ) }) : "-";
          }
          break;
        case "boolean":
          v = /* @__PURE__ */ jsxRuntimeExports.jsx(
            Chip,
            {
              type: "normal",
              sx: (theme) => {
                var _a2, _b2, _c2, _d2;
                return {
                  ...renderedCellValue ? {
                    backgroundColor: (_a2 = theme.palette) == null ? void 0 : _a2.theme.tertiary4[200],
                    color: (_b2 = theme.palette) == null ? void 0 : _b2.theme.tertiary4[900]
                  } : {
                    backgroundColor: (_c2 = theme.palette) == null ? void 0 : _c2.theme.tertiary6[200],
                    color: (_d2 = theme.palette) == null ? void 0 : _d2.theme.tertiary6[900]
                  }
                };
              },
              label: /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight: "medium", color: "inherit", children: ((_d = column == null ? void 0 : column.typeBooleanLabels) == null ? void 0 : _d[renderedCellValue]) || "-" })
            }
          );
          break;
        case "jsonArray":
          v = jsonArrayToString(renderedCellValue);
          break;
        case "custom":
        case "custom_link":
          v = customizeValue == null ? void 0 : customizeValue(row, column.accessorKey, renderedCellValue);
          break;
        case "toFixed":
          v = toFixedWithNumbers(renderedCellValue);
          break;
      }
      if (redirectionPathWithId && column.type != "custom_link") {
        const id = row.original[idField || "id"];
        if (id) {
          const path = redirectionPathWithId instanceof Function ? generateRouteWithId(redirectionPathWithId(row), id == null ? void 0 : id.toString()) : generateRouteWithId(redirectionPathWithId, id == null ? void 0 : id.toString());
          return /* @__PURE__ */ jsxRuntimeExports.jsx(Link, { to: path, children: v });
        }
      } else if (redirectionLink && column.type != "custom_link") {
        const id = row.original[idField || "id"];
        const path = redirectionLink instanceof Function ? generateRouteWithId(redirectionLink(row), id == null ? void 0 : id.toString()) : generateRouteWithId(redirectionLink, id == null ? void 0 : id.toString());
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          Link,
          {
            to: path,
            state: redirectionLinkState == null ? void 0 : redirectionLinkState(row),
            children: v
          }
        );
      }
      return v;
    },
    ...Boolean(enableFooter) && {
      Footer: ({ column: column2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(DefaultAggregation, { data: rows, column: String(column2.id) })
    }
  }));
};
const renderEmptyRowsFallback = (text) => /* @__PURE__ */ jsxRuntimeExports.jsxs(Box, { className: "no-data", children: [
  /* @__PURE__ */ jsxRuntimeExports.jsx("img", { src: images.common.tableNoData }),
  /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s3", weight: "medium", color: "theme.secondary.1000", children: text })
] });
const renderValueField = (label, value, t, formatFn) => {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(ValueField, { label: t == null ? void 0 : t(label), children: formatFn ? formatFn(value) : value ?? "-" }, label);
};
const formateValueByType = ({
  value,
  type,
  format,
  weight
}) => {
  const numberTypes = ["number", "amount", "toFixed"];
  const valueCheck = [null, void 0, "0"];
  if (valueCheck.includes(value)) return /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight, color: "theme.neutral.1000", children: (numberTypes == null ? void 0 : numberTypes.includes(type)) ? value : value || "-" });
  switch (type) {
    case "date":
      return dayjs(value).isValid() ? formatDate(value, format) : value;
    case "toFixed":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight, color: "theme.neutral.1000", children: value ? toFixedWithNumbers(Number(value)) : "-" });
    case "amount":
      return /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight, color: "theme.neutral.1000", children: value ? formatAmountWithCurrency(Number(value)) : "-" });
    default:
      return weight ? /* @__PURE__ */ jsxRuntimeExports.jsx(Typography, { type: "s4", weight, color: "theme.neutral.1000", children: value || "-" }) : value || "-";
  }
};
const setCompany = (value) => {
  var _a;
  const { user } = useAuth();
  return {
    value: user == null ? void 0 : user.company_id,
    options: [{
      label: (_a = user == null ? void 0 : user.company_data) == null ? void 0 : _a.name,
      value: user == null ? void 0 : user.company_id
    }]
  };
};
const configMapper = {
  "company": {
    callBack: setCompany
  }
};
const getFirstNonSectionField = (formData) => {
  const firstField = formData == null ? void 0 : formData.find((field) => !field.is_section_field);
  return firstField;
};
const formBuilderDeConversion = (formData) => {
  const outputData = {};
  if (formData.length === 0) {
    return outputData;
  }
  const firstItem = getFirstNonSectionField(formData);
  if (firstItem == null ? void 0 : firstItem.tab_name) {
    outputData.tab = [];
    let currentTab = null;
    let currentSection = null;
    let otherSectionDetails = {};
    let sectionOrder = null;
    formData.forEach((item) => {
      var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
      if (item == null ? void 0 : item.is_section_field) {
        otherSectionDetails = {
          field_type: item == null ? void 0 : item.field_type,
          label: item == null ? void 0 : item.label,
          is_accordion: item == null ? void 0 : item.is_accordion,
          is_section_field: item == null ? void 0 : item.is_section_field,
          section_type: item == null ? void 0 : item.section_type,
          form_switcher_label: item == null ? void 0 : item.form_switcher_label,
          form_switcher_name: item == null ? void 0 : item.form_switcher_name,
          switcher_forms: item == null ? void 0 : item.switcher_forms,
          disabled: Boolean(item == null ? void 0 : item.disabled)
        };
        currentSection = null;
        sectionOrder = sectionOrder++;
      } else {
        if (!currentTab || currentTab.title !== item.tab_name) {
          currentTab = {
            tab_order: item.tab_order || 1,
            title: item.tab_name,
            data: []
          };
          const checkIfTabExist = outputData.tab.find((tab) => tab.title === (currentTab == null ? void 0 : currentTab.title));
          if (!checkIfTabExist) {
            outputData.tab.push(currentTab);
          } else {
            currentTab = checkIfTabExist;
          }
          currentSection = null;
        }
        if (!currentSection || currentSection.label !== item.section_name || sectionOrder !== item.section_order) {
          currentSection = {
            field_type: "section",
            label: item.section_name || "",
            is_accordion: (_a = item.field_properties) == null ? void 0 : _a.is_accordion,
            members: [],
            remove_section: item.is_system_field === true ? true : false
          };
          const checkIfSectionExist = currentTab.data.find((section) => section.label === (currentSection == null ? void 0 : currentSection.label));
          if (!checkIfSectionExist) {
            currentSection = { ...otherSectionDetails, ...currentSection };
            currentTab.data.push(currentSection);
          } else {
            currentSection = checkIfSectionExist;
          }
          otherSectionDetails = null;
        }
        sectionOrder = item.section_order;
        const thenValidations = ((_c = (_b = item == null ? void 0 : item.validation) == null ? void 0 : _b.find((v) => v.type === "when")) == null ? void 0 : _c.thenValidations) || [];
        const member = {
          ...item,
          id: `${Date.now()}-${Math.random()}`,
          field_type: item.field_type === "media" ? "file" : item.field_type || "text",
          type: item.is_system_field ? "system" : "custom",
          label: item.label || "",
          placeholder: item.placeholder || "",
          default_value: item.default_value || "",
          ...(item == null ? void 0 : item.time_format) && (item == null ? void 0 : item.field_type) === "time" && { option: item == null ? void 0 : item.time_format },
          ...(item == null ? void 0 : item.currency) && (item == null ? void 0 : item.field_type) === "currency" && { option: item == null ? void 0 : item.currency },
          ...item.field_type === "text" && {
            min_length: ((_d = item.validation.find(
              (v) => v.type === "min_length"
            )) == null ? void 0 : _d.value) || null
          },
          ...item.field_type === "text" && {
            max_length: ((_e = item.validation.find(
              (v) => v.type === "max_length"
            )) == null ? void 0 : _e.value) || null
          },
          ...item.field_type === "number" && {
            min_length: ((_f = item.validation.find((v) => v.type === "min_val")) == null ? void 0 : _f.value) || null
          },
          ...item.field_type === "number" && {
            max_length: ((_g = item.validation.find((v) => v.type === "max_val")) == null ? void 0 : _g.value) || null
          },
          ...(item.is_multiline !== void 0 || item.field_properties.is_multiline !== void 0) && {
            is_multiline: item.is_multiline || item.field_properties.is_multiline
          },
          is_required: ((_h = item.validation.find((v) => v.type === "required")) == null ? void 0 : _h.value) || ((_i = thenValidations == null ? void 0 : thenValidations.find((v) => v.type === "required")) == null ? void 0 : _i.value) || false,
          is_unique: ((_j = item.validation.find((v) => v.type === "unique")) == null ? void 0 : _j.value) || false,
          section_order: item.section_order || 0,
          ...item.field_properties.float_step && {
            float_step: item.field_properties.float_step.toString()
          },
          ...item.field_properties.options && {
            options: item.field_properties.options
          },
          ...item.field_properties.is_multiselect !== void 0 && {
            is_multiselect: item.field_properties.is_multiselect
          },
          ...((_k = item.field_properties) == null ? void 0 : _k.enable_footer) !== void 0 && {
            enable_footer: Boolean(item.field_properties.enable_footer)
          },
          ...((_l = item.field_properties) == null ? void 0 : _l.footer_action) !== void 0 && {
            footer_action: item.field_properties.footer_action || "add"
          },
          ...item.field_type === "date" && {
            is_future_dates_allowed: ((_m = item.validation.find(
              (v) => v.type === "is_future_dates_allowed"
            )) == null ? void 0 : _m.value) || null
          },
          ...item.field_type === "date" && {
            is_past_dates_allowed: ((_n = item.validation.find(
              (v) => v.type === "is_past_dates_allowed"
            )) == null ? void 0 : _n.value) || null
          },
          ...(item.field_type === "image" || item.field_type === "media" || item.field_type === "file") && {
            max_size: ((_o = item.validation.find(
              (v) => v.type === "max_file_size"
            )) == null ? void 0 : _o.value) || void 0,
            is_multiple: (_p = item.field_properties) == null ? void 0 : _p.is_multiple
          },
          ...(item.field_type === "toggleButton" || item.field_type === "checkbox" || item.field_type === "radioButton") && {
            title: ((_q = item.field_properties) == null ? void 0 : _q.title) ? (_r = item.field_properties) == null ? void 0 : _r.title : "",
            title_position: ((_s = item.field_properties) == null ? void 0 : _s.title_position) ?? "end",
            is_checked: (_t = item.field_properties) == null ? void 0 : _t.is_checked
          },
          ...item.field_type === "table" && {
            table: (_u = item.field_properties) == null ? void 0 : _u.table,
            table_columns: convertTableColumns((_v = item.field_properties) == null ? void 0 : _v.table_columns),
            table_rows: (_w = item.field_properties) == null ? void 0 : _w.table_rows,
            otherButtons: ((_x = item.field_properties) == null ? void 0 : _x.other_buttons) || []
          }
        };
        if (currentSection) {
          currentSection.members.push(member);
          if (currentSection.members.some((member2) => member2.type === "system")) {
            currentSection.remove_section = true;
          } else {
            currentSection.remove_section = false;
          }
          currentTab.remove_tab = currentTab.data.some(
            (section) => section.members.some(
              (member2) => member2.type === "system"
            )
          );
        }
      }
    });
  } else {
    outputData.section = [];
    let currentSection = null;
    let otherSectionDetails = {};
    let sectionOrder = null;
    formData.forEach(
      (item) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C;
        if (item.is_section_field) {
          otherSectionDetails = {
            field_type: item == null ? void 0 : item.field_type,
            label: item == null ? void 0 : item.label,
            is_accordion: item == null ? void 0 : item.is_accordion,
            is_section_field: item == null ? void 0 : item.is_section_field,
            section_type: item == null ? void 0 : item.section_type,
            form_switcher_label: item == null ? void 0 : item.form_switcher_label,
            form_switcher_name: item == null ? void 0 : item.form_switcher_name,
            switcher_forms: item == null ? void 0 : item.switcher_forms,
            disabled: Boolean(item == null ? void 0 : item.disabled)
          };
          sectionOrder = sectionOrder++;
          currentSection = null;
        } else {
          if (!currentSection || currentSection.label !== item.section_name || sectionOrder !== item.section_order) {
            currentSection = {
              field_type: "section",
              label: item.section_name || "",
              is_accordion: (_a = item.field_properties) == null ? void 0 : _a.is_accordion,
              members: [],
              remove_section: item.is_system_field === true ? true : false
            };
            const checkIfSectionExist = (_b = outputData == null ? void 0 : outputData.section) == null ? void 0 : _b.find((section) => section.label === (currentSection == null ? void 0 : currentSection.label));
            if (!checkIfSectionExist) {
              currentSection = { ...otherSectionDetails, ...currentSection };
              outputData.section.push(currentSection);
            } else {
              currentSection = checkIfSectionExist;
            }
            otherSectionDetails = null;
          }
          sectionOrder = item.section_order;
          const thenValidations = ((_d = (_c = item == null ? void 0 : item.validation) == null ? void 0 : _c.find((v) => v.type === "when")) == null ? void 0 : _d.thenValidations) || [];
          const member = {
            ...item,
            id: `${Date.now()}-${Math.random()}`,
            field_type: item.field_type === "media" ? "file" : item.field_type || "text",
            type: item.is_system_field ? "system" : "custom",
            label: item.label,
            placeholder: item.placeholder || "",
            default_value: item.default_value || "",
            ...(item == null ? void 0 : item.time_format) && (item == null ? void 0 : item.field_type) === "time" && { option: item == null ? void 0 : item.time_format },
            ...(item == null ? void 0 : item.currency) && (item == null ? void 0 : item.field_type) === "currency" && { option: item == null ? void 0 : item.currency },
            ...item.field_type === "text" && {
              min_length: ((_e = item.validation.find(
                (v) => v.type === "min_length"
              )) == null ? void 0 : _e.value) || null
            },
            ...item.field_type === "text" && {
              max_length: ((_f = item.validation.find(
                (v) => v.type === "max_length"
              )) == null ? void 0 : _f.value) || null
            },
            ...item.field_type === "number" && {
              min_length: ((_g = item.validation.find(
                (v) => v.type === "min_val"
              )) == null ? void 0 : _g.value) || null
            },
            ...item.field_type === "number" && {
              max_length: ((_h = item.validation.find(
                (v) => v.type === "max_val"
              )) == null ? void 0 : _h.value) || null
            },
            ...(item.is_multiline !== void 0 || ((_i = item.field_properties) == null ? void 0 : _i.is_multiline) !== void 0) && {
              is_multiline: item.is_multiline || item.field_properties.is_multiline
            },
            is_required: ((_j = item.validation.find((v) => v.type === "required")) == null ? void 0 : _j.value) || ((_k = thenValidations == null ? void 0 : thenValidations.find((v) => v.type === "required")) == null ? void 0 : _k.value) || false,
            is_unique: ((_l = item.validation.find((v) => v.type === "unique")) == null ? void 0 : _l.value) || false,
            section_order: item.section_order || 0,
            ...((_m = item.field_properties) == null ? void 0 : _m.float_step) && {
              float_step: Number(item.field_properties.float_step)
            },
            ...((_n = item.field_properties) == null ? void 0 : _n.options) && {
              options: item.field_properties.options
            },
            ...((_o = item.field_properties) == null ? void 0 : _o.is_multiselect) !== void 0 && {
              is_multiselect: item.field_properties.is_multiselect
            },
            ...((_p = item.field_properties) == null ? void 0 : _p.enable_footer) !== void 0 && {
              enable_footer: Boolean(item.field_properties.enable_footer)
            },
            ...((_q = item.field_properties) == null ? void 0 : _q.footer_action) !== void 0 && {
              footer_action: item.field_properties.footer_action || "add"
            },
            ...item.field_type === "date" && {
              is_future_dates_allowed: ((_r = item.validation.find(
                (v) => v.type === "is_future_dates_allowed"
              )) == null ? void 0 : _r.value) || null
            },
            ...item.field_type === "date" && {
              is_past_dates_allowed: ((_s = item.validation.find(
                (v) => v.type === "is_past_dates_allowed"
              )) == null ? void 0 : _s.value) || null
            },
            ...(item.field_type === "image" || item.field_type === "media" || item.field_type === "file") && {
              max_size: ((_t = item.validation.find(
                (v) => v.type === "max_file_size"
              )) == null ? void 0 : _t.value) || void 0,
              is_multiple: (_u = item.field_properties) == null ? void 0 : _u.is_multiple
            },
            ...(item.field_type === "toggleButton" || item.field_type === "checkbox") && {
              title: ((_v = item.field_properties) == null ? void 0 : _v.title) ? (_w = item.field_properties) == null ? void 0 : _w.title : item.label,
              title_position: ((_x = item.field_properties) == null ? void 0 : _x.title_position) ?? "end",
              is_checked: (_y = item.field_properties) == null ? void 0 : _y.is_checked
            },
            ...item.field_type === "table" && {
              table: (_z = item.field_properties) == null ? void 0 : _z.table,
              table_columns: convertTableColumns((_A = item.field_properties) == null ? void 0 : _A.table_columns),
              table_rows: (_B = item.field_properties) == null ? void 0 : _B.table_rows,
              otherButtons: ((_C = item.field_properties) == null ? void 0 : _C.other_buttons) || []
            }
          };
          currentSection.members.push(member);
          if (currentSection.members.some((member2) => member2.type === "system")) {
            currentSection.remove_section = true;
          } else {
            currentSection.remove_section = false;
          }
        }
      }
    );
  }
  return outputData;
};
function formatText(key) {
  return key ? key.split(/[:_-]/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ") : key;
}
const convertTableColumns = (columns) => {
  if (!Array.isArray(columns)) return [];
  return columns.map((column) => {
    if (typeof column === "object") {
      return { ...column };
    } else {
      const colArr = column.split(".").filter((str) => str);
      const header = colArr.length ? colArr.length > 1 ? formatText(colArr[colArr.length - 1]) : formatText(colArr[0]) : "-";
      return {
        header,
        accessorKey: column,
        visible: true
      };
    }
  });
};
export {
  Chip as C,
  DefaultAggregation as D,
  Menu as M,
  ValueField as V,
  convertTableColumns as a,
  formateValueByType as b,
  configMapper as c,
  getFileNamesFromUrlsAsLink as d,
  renderValueField as e,
  formBuilderDeConversion as f,
  getFileNamesFromUrls as g,
  aggregationFns as h,
  renderEmptyRowsFallback as r,
  transformTableColumns as t
};
//# sourceMappingURL=form-builder-deconversion-mG9WaeP0.esm.js.map
