import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState } from 'react';
import { _humanize, isNotEmpty, capitalize, snakeToCamelCase, _capitalize, isPresent } from '@bigbinary/neeto-cist';
import { SINGULAR, DEFAULT_PAGE_SIZE, DEFAULT_PAGE_INDEX } from '@bigbinary/neeto-commons-frontend/constants';
import { useQueryParams } from '@bigbinary/neeto-commons-frontend/react-utils';
import NoData from '@bigbinary/neetoui/NoData';
import Table from '@bigbinary/neetoui/Table';
import Typography from '@bigbinary/neetoui/Typography';
import Spinner from '@bigbinary/neetoui/Spinner';
import { Trans, useTranslation } from 'react-i18next';
import Container from './Container.js';
import Header from './Header.js';
import SubHeader from './SubHeader.js';
import TableWrapper from './TableWrapper.js';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import Pane from '@bigbinary/neetoui/Pane';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { t } from 'i18next';
import { dateFormat } from '@bigbinary/neeto-commons-frontend/utils';
import Button from '@bigbinary/neetoui/Button';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import 'classnames';
import './index-DAYCJu79.js';
import './_commonjsHelpers-BFTU3MAI.js';
import './inject-css-C2dztUxs.js';
import './Breadcrumbs.js';
import '@bigbinary/neeto-commons-frontend/utils/general';
import 'react-router-dom';
import './HelpPopover.js';
import '@bigbinary/neeto-icons/Help';
import '@bigbinary/neetoui/Popover';
import './MoreDropdown.js';
import '@bigbinary/neeto-icons/MenuHorizontal';
import '@bigbinary/neeto-icons/MenuVertical';
import '@bigbinary/neetoui/Dropdown';
import '@bigbinary/neetoui/Tooltip';
import 'ramda';
import './Search.js';
import '@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce';
import '@bigbinary/neeto-commons-frontend/react-utils/useQueryParams';
import '@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect';
import '@bigbinary/neeto-icons/Search';
import '@bigbinary/neetoui/Input';
import '@bigbinary/neeto-icons/Column';
import './Columns-Bs-Y6jgW.js';
import '@babel/runtime/helpers/toConsumableArray';
import '@dnd-kit/core';
import '@dnd-kit/sortable';
import '@bigbinary/neetoui/Checkbox';
import '@bigbinary/neetoui/Label';
import '@bigbinary/neeto-icons/Reorder';
import '@bigbinary/neeto-commons-frontend/react-utils/useMutationWithInvalidation';
import '@bigbinary/neeto-icons/Download';
import '@bigbinary/neeto-filters-frontend/Filters';
import '@bigbinary/neeto-icons/Filter';

var LabelledDetail = function LabelledDetail(_ref) {
  var label = _ref.label,
    value = _ref.value;
  return /*#__PURE__*/jsx(Typography, {
    className: "mb-4",
    style: "body2",
    children: /*#__PURE__*/jsx(Trans, {
      components: {
        strong: /*#__PURE__*/jsx("strong", {})
      },
      i18nKey: "neetoMolecules.auditLogs.additionalDetails.".concat(label),
      values: {
        value: value
      }
    })
  });
};

var DATE_FORMATS = {
  "%d/%m/%Y": "DD/MM/YYYY",
  "%m/%d/%Y": "MM/DD/YYYY",
  "%Y/%m/%d": "YYYY/MM/DD"
};
var DETAILS_KEYS = {
  AFFECTED_EMAIL: "affectedEmail",
  ERROR_MESSAGE: "errorMessage",
  NAME: "name",
  ORGANIZATION_ROLE: "organizationRole",
  GENERIC_DETAILS: "details",
  ADDED_PERMISSIONS: "addedPermissions",
  REMOVED_PERMISSIONS: "removedPermissions"
};
var EMAILS_TABLE_COLUMN_DATA = [{
  title: t("neetoMolecules.auditLogs.details.emails.title"),
  key: "email",
  dataIndex: "email"
}];
var CHANGELOG_COLUMN_DATA = [{
  title: t("neetoMolecules.auditLogs.details.changelog.field"),
  key: "field",
  dataIndex: "field",
  ellipsis: false
}, {
  title: t("neetoMolecules.auditLogs.details.changelog.from"),
  key: "from",
  dataIndex: "from",
  width: "38%",
  ellipsis: false
}, {
  title: t("neetoMolecules.auditLogs.details.changelog.to"),
  key: "to",
  dataIndex: "to",
  width: "38%",
  ellipsis: false
}];

var formatToFromValue = function formatToFromValue(value) {
  if (value === true) {
    return t("neetoMolecules.auditLogs.details.changelog.true");
  }
  if (value === false) {
    return t("neetoMolecules.auditLogs.details.changelog.false");
  }
  if (value === null) return "-";
  return value;
};
var transformDateFormat = function transformDateFormat(rawDateFormat) {
  return DATE_FORMATS[rawDateFormat];
};
var getFormattedValue = function getFormattedValue(field, value) {
  return field === "dateFormat" ? transformDateFormat(value) : formatToFromValue(value);
};
var formatEmails = function formatEmails(emails) {
  return emails.map(function (email) {
    return {
      email: email
    };
  });
};
var formatChangeLog = function formatChangeLog(changes) {
  return Object.entries(changes).map(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      field = _ref2[0],
      _ref2$ = _ref2[1],
      from = _ref2$.from,
      to = _ref2$.to;
    var formattedField = _humanize(field);
    return {
      field: formattedField,
      from: getFormattedValue(field, from),
      to: getFormattedValue(field, to)
    };
  });
};
var getFullName = function getFullName(firstName) {
  var lastName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  return "".concat(firstName, " ").concat(lastName).trim();
};
var getLabel = function getLabel(_ref3) {
  var firstName = _ref3.firstName,
    lastName = _ref3.lastName,
    organizationRole = _ref3.organizationRole;
  if (firstName || lastName) {
    return DETAILS_KEYS.NAME;
  }
  if (organizationRole) {
    return DETAILS_KEYS.ORGANIZATION_ROLE;
  }
  return DETAILS_KEYS.GENERIC_DETAILS;
};
var formatPermissionsChangeLog = function formatPermissionsChangeLog(_ref4) {
  var from = _ref4.from,
    to = _ref4.to;
  return [{
    field: t("neetoMolecules.auditLogs.details.permissions.description"),
    from: getFormattedValue("description", from),
    to: getFormattedValue("description", to)
  }];
};
var transformPermissions = function transformPermissions(permissions) {
  return permissions.map(function (permission) {
    var humanizedParts = permission.split(".").map(_humanize);
    return humanizedParts.join(" - ");
  }).join(", ");
};

var GenericChangelog = function GenericChangelog(_ref) {
  var details = _ref.details;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _details$email = details.email,
    email = _details$email === void 0 ? "" : _details$email,
    _details$changes = details.changes,
    changes = _details$changes === void 0 ? {} : _details$changes,
    _details$errorMessage = details.errorMessage,
    errorMessage = _details$errorMessage === void 0 ? "" : _details$errorMessage,
    status = details.status;
  return /*#__PURE__*/jsxs("div", {
    children: [/*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.AFFECTED_EMAIL,
      value: email
    }), isNotEmpty(changes) && status === "success" ? /*#__PURE__*/jsx("div", {
      className: "w-full min-w-0 max-w-full",
      children: /*#__PURE__*/jsx(Table, {
        columnData: CHANGELOG_COLUMN_DATA,
        enableColumnFreeze: false,
        enableColumnResize: false,
        rowData: formatChangeLog(changes),
        scroll: {
          x: "100%"
        }
      })
    }) : /*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.ERROR_MESSAGE,
      value: errorMessage || t("neetoMolecules.auditLogs.noError")
    })]
  });
};

var PermissionsChangelog = function PermissionsChangelog(_ref) {
  var details = _ref.details;
  var _details$description = details.description,
    description = _details$description === void 0 ? {} : _details$description,
    _details$organization = details.organizationRole,
    organizationRole = _details$organization === void 0 ? "" : _details$organization,
    _details$addedPermiss = details.addedPermissions,
    addedPermissions = _details$addedPermiss === void 0 ? [] : _details$addedPermiss,
    _details$removedPermi = details.removedPermissions,
    removedPermissions = _details$removedPermi === void 0 ? [] : _details$removedPermi;
  return /*#__PURE__*/jsxs("div", {
    children: [/*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.ORGANIZATION_ROLE,
      value: organizationRole
    }), isNotEmpty(addedPermissions) && /*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.ADDED_PERMISSIONS,
      value: transformPermissions(addedPermissions)
    }), isNotEmpty(removedPermissions) && /*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.REMOVED_PERMISSIONS,
      value: transformPermissions(removedPermissions)
    }), isNotEmpty(description) && /*#__PURE__*/jsx("div", {
      className: "w-full min-w-0 max-w-full",
      children: /*#__PURE__*/jsx(Table, {
        columnData: CHANGELOG_COLUMN_DATA,
        enableColumnFreeze: false,
        enableColumnResize: false,
        rowData: formatPermissionsChangeLog(description),
        scroll: {
          x: "100%"
        }
      })
    })]
  });
};

var Emails = function Emails(_ref) {
  var details = _ref.details;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _details$emails = details.emails,
    emails = _details$emails === void 0 ? [] : _details$emails,
    status = details.status,
    _details$errorMessage = details.errorMessage,
    errorMessage = _details$errorMessage === void 0 ? "" : _details$errorMessage;
  return /*#__PURE__*/jsx(Fragment, {
    children: isNotEmpty(emails) && status === "success" ? /*#__PURE__*/jsx("div", {
      className: "w-full min-w-0 max-w-full",
      children: /*#__PURE__*/jsx(Table, {
        columns: EMAILS_TABLE_COLUMN_DATA,
        enableColumnFreeze: false,
        enableColumnResize: false,
        loading: false,
        rowData: formatEmails(emails),
        scroll: {
          x: "100%"
        }
      })
    }) : /*#__PURE__*/jsx(LabelledDetail, {
      label: DETAILS_KEYS.ERROR_MESSAGE,
      value: errorMessage || t("neetoMolecules.auditLogs.noError")
    })
  });
};

var GenericDetails = function GenericDetails(_ref) {
  var details = _ref.details;
  var _details$firstName = details.firstName,
    firstName = _details$firstName === void 0 ? "" : _details$firstName,
    _details$lastName = details.lastName,
    lastName = _details$lastName === void 0 ? "" : _details$lastName,
    _details$organization = details.organizationRole,
    organizationRole = _details$organization === void 0 ? "" : _details$organization;
  var name = getFullName(firstName, lastName);
  var label = getLabel({
    firstName: firstName,
    lastName: lastName,
    organizationRole: organizationRole
  });
  var value = name || organizationRole || JSON.stringify(details);
  return /*#__PURE__*/jsx(LabelledDetail, {
    label: label,
    value: value
  });
};

var AUDIT_LOGS_QUERY_KEY = "audit-logs";
var ACTIONS = {
  INVITED_USERS: "invitedUsers",
  USER_SIGNED_UP: "userSignedUp",
  UPDATED_USER: "updatedUser",
  BULK_UPDATE_USERS: "bulkUpdateUsers",
  UPDATED_USER_PROFILE: "updatedUserProfile",
  CREATED_ROLE: "createdRole",
  UPDATED_ROLE: "updatedRole",
  DELETED_ROLE: "deletedRole"
};
var ADDITIONAL_DETAILS_KEYS = {
  ACTION: "action",
  PERFORMED_BY: "performedBy",
  PERFORMED_AT: "performedAt",
  PRODUCT: "product"
};
var DETAILS_COMPONENT_MAP = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, ACTIONS.INVITED_USERS, Emails), ACTIONS.BULK_UPDATE_USERS, Emails), ACTIONS.USER_SIGNED_UP, GenericDetails), ACTIONS.UPDATED_USER, GenericChangelog), ACTIONS.UPDATED_USER_PROFILE, GenericChangelog), ACTIONS.CREATED_ROLE, GenericDetails), ACTIONS.UPDATED_ROLE, PermissionsChangelog), ACTIONS.DELETED_ROLE, GenericDetails);

var _excluded$1 = ["status"];
function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var transformAction = function transformAction(action) {
  return snakeToCamelCase(action.replace("audit_logs.organization.", ""));
};
var transformLogsForTable = function transformLogsForTable(logs) {
  return logs.map(function (_ref) {
    var id = _ref.id,
      action = _ref.key,
      _ref$metadata = _ref.metadata,
      status = _ref$metadata.status,
      restOfMetadata = _objectWithoutProperties(_ref$metadata, _excluded$1),
      _ref$performer$name = _ref.performer.name,
      performedBy = _ref$performer$name === void 0 ? "" : _ref$performer$name,
      performedAt = _ref.updatedAt;
    var transformedAction = transformAction(action);
    var formattedPerformedAt = dateFormat.dateTime(performedAt);
    return {
      id: id,
      action: transformedAction,
      status: capitalize(status),
      performedAt: formattedPerformedAt,
      performedBy: performedBy,
      additionalDetails: _objectSpread$2(_objectSpread$2({}, restOfMetadata), {}, {
        action: transformedAction,
        performedAt: formattedPerformedAt,
        performedBy: performedBy,
        status: status
      })
    };
  });
};
var getColumnData = function getColumnData(handleClick) {
  return [{
    title: t("neetoMolecules.auditLogs.table.headers.action", SINGULAR),
    key: "action",
    dataIndex: "action",
    render: function render(action, _ref2) {
      var additionalDetails = _ref2.additionalDetails;
      return /*#__PURE__*/jsx(Button, {
        "data-testid": "action-link-button",
        label: t("neetoMolecules.auditLogs.actions.".concat(action)),
        style: "link",
        onClick: function onClick() {
          return handleClick(additionalDetails);
        }
      });
    },
    width: 200
  }, {
    title: t("neetoMolecules.auditLogs.table.headers.status"),
    key: "status",
    dataIndex: "status",
    width: 150
  }, {
    title: t("neetoMolecules.auditLogs.table.headers.performedBy"),
    key: "performedBy",
    dataIndex: "performedBy",
    width: 160
  }, {
    title: t("neetoMolecules.auditLogs.table.headers.performedAt"),
    key: "performedAt",
    dataIndex: "performedAt",
    width: 160
  }];
};
var getComponentForDetail = function getComponentForDetail(action) {
  return DETAILS_COMPONENT_MAP[action] || GenericDetails;
};

var _excluded = ["message", "action", "performedBy", "performedAt", "via"];
var AdditionalDetails = function AdditionalDetails(_ref) {
  var additionalDetails = _ref.additionalDetails,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var message = additionalDetails.message,
    defaultAction = additionalDetails.action,
    performedBy = additionalDetails.performedBy,
    performedAt = additionalDetails.performedAt,
    product = additionalDetails.via,
    details = _objectWithoutProperties(additionalDetails, _excluded);
  var action = message || t("neetoMolecules.auditLogs.actions.".concat(defaultAction));
  var DetailComponent = getComponentForDetail(defaultAction);
  return /*#__PURE__*/jsxs(Pane, {
    isOpen: isOpen,
    onClose: onClose,
    "data-testid": "additional-details-pane",
    size: "large",
    children: [/*#__PURE__*/jsx(Pane.Header, {
      children: /*#__PURE__*/jsx(Typography, {
        style: "h2",
        children: t("neetoMolecules.auditLogs.additionalDetails.title")
      })
    }), /*#__PURE__*/jsx(Pane.Body, {
      hasFooter: false,
      children: /*#__PURE__*/jsxs(Fragment, {
        children: [/*#__PURE__*/jsx(LabelledDetail, {
          label: ADDITIONAL_DETAILS_KEYS.ACTION,
          value: action
        }), /*#__PURE__*/jsx(LabelledDetail, {
          label: ADDITIONAL_DETAILS_KEYS.PERFORMED_BY,
          value: performedBy
        }), /*#__PURE__*/jsx(LabelledDetail, {
          label: ADDITIONAL_DETAILS_KEYS.PERFORMED_AT,
          value: performedAt
        }), /*#__PURE__*/jsx(LabelledDetail, {
          label: ADDITIONAL_DETAILS_KEYS.PRODUCT,
          value: _capitalize(product)
        }), /*#__PURE__*/jsx(DetailComponent, {
          details: details
        })]
      })
    })]
  });
};

var fetchAuditLogs = function fetchAuditLogs(params) {
  return axios.get("api/v1/audit_logs", {
    params: params
  });
};
var auditLogsApi = {
  fetchAuditLogs: fetchAuditLogs
};

function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var useFetchAuditLogs = function useFetchAuditLogs(_ref) {
  var params = _ref.params,
    _ref$options = _ref.options,
    options = _ref$options === void 0 ? {} : _ref$options;
  return useQuery(_objectSpread$1({
    queryKey: [AUDIT_LOGS_QUERY_KEY, params],
    queryFn: function queryFn() {
      return auditLogsApi.fetchAuditLogs(params);
    }
  }, options));
};

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var AuditLogs = function AuditLogs(_ref) {
  var headerProps = _ref.headerProps,
    noDataHelpText = _ref.noDataHelpText,
    noDataTitle = _ref.noDataTitle;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isAdditionalDetailsPaneOpen = _useState2[0],
    setIsAdditionalDetailsPaneOpen = _useState2[1];
  var _useState3 = useState({}),
    _useState4 = _slicedToArray(_useState3, 2),
    additionalDetails = _useState4[0],
    setAdditionalDetails = _useState4[1];
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var _useQueryParams = useQueryParams(),
    _useQueryParams$page = _useQueryParams.page,
    page = _useQueryParams$page === void 0 ? DEFAULT_PAGE_INDEX : _useQueryParams$page;
  var _useFetchAuditLogs = useFetchAuditLogs({
      params: {
        page: page
      }
    }),
    _useFetchAuditLogs$da = _useFetchAuditLogs.data,
    _useFetchAuditLogs$da2 = _useFetchAuditLogs$da === void 0 ? {} : _useFetchAuditLogs$da,
    _useFetchAuditLogs$da3 = _useFetchAuditLogs$da2.auditLogs,
    auditLogs = _useFetchAuditLogs$da3 === void 0 ? [] : _useFetchAuditLogs$da3,
    _useFetchAuditLogs$da4 = _useFetchAuditLogs$da2.totalCount,
    totalCount = _useFetchAuditLogs$da4 === void 0 ? 0 : _useFetchAuditLogs$da4,
    isLoading = _useFetchAuditLogs.isLoading,
    isFetching = _useFetchAuditLogs.isFetching;
  var handleClick = function handleClick(additionalDetails) {
    setIsAdditionalDetailsPaneOpen(true);
    setAdditionalDetails(additionalDetails);
  };
  var handleClose = function handleClose() {
    setIsAdditionalDetailsPaneOpen(false);
    setAdditionalDetails({});
  };
  if (isLoading) {
    return /*#__PURE__*/jsx("div", {
      className: "flex h-full w-full items-center justify-center",
      children: /*#__PURE__*/jsx(Spinner, {})
    });
  }
  return /*#__PURE__*/jsxs(Container, {
    children: [/*#__PURE__*/jsx(Header, _objectSpread({
      title: t("neetoMolecules.auditLogs.title")
    }, headerProps)), /*#__PURE__*/jsx(SubHeader, {
      leftActionBlock: isPresent(auditLogs) && /*#__PURE__*/jsx(Typography, {
        weight: "semibold",
        children: t("neetoMolecules.auditLogs.logsCount", {
          count: totalCount
        })
      })
    }), /*#__PURE__*/jsx(TableWrapper, {
      className: "mt-5",
      hasPagination: totalCount > DEFAULT_PAGE_SIZE,
      children: isPresent(auditLogs) ? /*#__PURE__*/jsx(Table, {
        totalCount: totalCount,
        fixedHeight: true,
        columnData: getColumnData(handleClick),
        currentPageNumber: parseInt(page),
        "data-testid": "audit-logs-table",
        defaultPageSize: DEFAULT_PAGE_SIZE,
        enableColumnFreeze: false,
        loading: isFetching,
        rowData: transformLogsForTable(auditLogs)
      }) : /*#__PURE__*/jsx("div", {
        className: "flex h-full w-full items-center justify-center",
        children: /*#__PURE__*/jsx(NoData, {
          helpText: noDataHelpText,
          title: noDataTitle || t("neetoMolecules.auditLogs.noData")
        })
      })
    }), /*#__PURE__*/jsx(AdditionalDetails, {
      additionalDetails: additionalDetails,
      isOpen: isAdditionalDetailsPaneOpen,
      onClose: handleClose
    })]
  });
};

export { AuditLogs as default };
//# sourceMappingURL=AuditLogs.js.map
