import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { snakeToCamelCase, humanize, isNotEmpty, isPresent } from '@bigbinary/neeto-cist';
import { 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 Spinner from '@bigbinary/neetoui/Spinner';
import Pagination from '@bigbinary/neetoui/Pagination';
import { Trans as Trans$1, useTranslation } from 'react-i18next';
import Container from './Container.js';
import Header from './Header.js';
import classnames from 'classnames';
import { dateFormat } from '@bigbinary/neeto-commons-frontend/utils';
import Typography from '@bigbinary/neetoui/Typography';
import User from '@bigbinary/neeto-icons/User';
import UserAdd from '@bigbinary/neeto-icons/UserAdd';
import UserCircle from '@bigbinary/neeto-icons/UserCircle';
import UserRemove from '@bigbinary/neeto-icons/UserRemove';
import UserSettings from '@bigbinary/neeto-icons/UserSettings';
import CustomDomain from '@bigbinary/neeto-icons/CustomDomain';
import GoogleCalendar from '@bigbinary/neeto-icons/misc/GoogleCalendar';
import Zoom from '@bigbinary/neeto-icons/misc/Zoom';
import Stripe from '@bigbinary/neeto-icons/misc/Stripe';
import StripeTypeface from '@bigbinary/neeto-icons/misc/StripeTypeface';
import { values } from 'ramda';
import { globalProps } from '@bigbinary/neeto-commons-frontend/initializers';
import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import { createElement } from 'react';
import './index-DAYCJu79.js';
import './_commonjsHelpers-BFTU3MAI.js';
import './inject-css-C2dztUxs.js';
import '@babel/runtime/helpers/objectWithoutProperties';
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/Button';
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 './Search.js';
import '@babel/runtime/helpers/slicedToArray';
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';

var _AUDIT_ICON_MAP;
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",
  CONNECTED_GOOGLE_CALENDER: "connectedGoogleCalendar",
  DISCONNECTED_GOOGLE_CALENDER: "disconnectedGoogleCalendar",
  CONNECTED_STRIPE_ACCOUNT: "connectedStripeAccount",
  DISCONNECTED_STRIPE_ACCOUNT: "disconnectedStripeAccount",
  CONNECTED_ZOOM_INTEGRATION: "connectedZoomIntegration",
  DISCONNECTED_ZOOM_INTEGRATION: "disconnectedZoomIntegration",
  CONNECTED_CUSTOM_DOMAIN: "connectedCustomDomain"
};
var AUDIT_ICON_MAP = (_AUDIT_ICON_MAP = {}, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_AUDIT_ICON_MAP, ACTIONS.INVITED_USERS, UserCircle), ACTIONS.USER_SIGNED_UP, UserAdd), ACTIONS.UPDATED_USER, User), ACTIONS.BULK_UPDATE_USERS, User), ACTIONS.UPDATED_USER_PROFILE, UserSettings), ACTIONS.CREATED_ROLE, UserAdd), ACTIONS.UPDATED_ROLE, UserSettings), ACTIONS.DELETED_ROLE, UserRemove), ACTIONS.CONNECTED_GOOGLE_CALENDER, GoogleCalendar), ACTIONS.DISCONNECTED_GOOGLE_CALENDER, GoogleCalendar), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_AUDIT_ICON_MAP, ACTIONS.CONNECTED_STRIPE_ACCOUNT, StripeTypeface), ACTIONS.DISCONNECTED_STRIPE_ACCOUNT, Stripe), ACTIONS.CONNECTED_ZOOM_INTEGRATION, Zoom), ACTIONS.DISCONNECTED_ZOOM_INTEGRATION, Zoom), ACTIONS.CONNECTED_CUSTOM_DOMAIN, CustomDomain));
var AUDIT_LOGS_PAGE_SIZE = 12;

function ownKeys$3(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$3(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$3(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var Trans = function Trans(_ref) {
  var i18nKey = _ref.i18nKey,
    _ref$additionalValues = _ref.additionalValues,
    additionalValues = _ref$additionalValues === void 0 ? {} : _ref$additionalValues,
    _ref$additionalCompon = _ref.additionalComponents,
    additionalComponents = _ref$additionalCompon === void 0 ? {} : _ref$additionalCompon;
  return /*#__PURE__*/jsx(Trans$1, {
    i18nKey: i18nKey,
    components: _objectSpread$3({
      Code: /*#__PURE__*/jsx(Typography, {
        className: "neeto-ui-rounded-md neeto-ui-bg-gray-100 p-1",
        component: "code",
        style: "body3"
      }),
      Semibold: /*#__PURE__*/jsx(Typography, {
        className: "n inline-block text-sm font-medium",
        component: "p"
      })
    }, additionalComponents),
    values: _objectSpread$3({
      productSuffix: globalProps.appName
    }, additionalValues)
  });
};

var formatChangedFields = function formatChangedFields(changes) {
  var fields = Object.keys(changes).map(function (field, index) {
    var change = changes[field];
    var element;
    if (change && isPresent(change.from)) {
      element = /*#__PURE__*/jsx("span", {
        children: /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.auditLogs.text.updatedFieldsWithPreviousValue",
          additionalValues: {
            field: humanize(field),
            from: change.from,
            to: change.to
          }
        })
      }, field);
    } else {
      element = /*#__PURE__*/jsx("span", {
        children: /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            field: humanize(field),
            to: change.to
          },
          i18nKey: "neetoMolecules.auditLogs.text.updatedFieldsWithNewValue"
        })
      }, field);
    }
    return index > 0 ? [/*#__PURE__*/jsx("span", {
      children: ", "
    }, "sep-".concat(field)), element] : element;
  });
  return fields.flat();
};
var transformAction = function transformAction(action) {
  return snakeToCamelCase(action.replace("audit_logs.organization.", ""));
};
var constructAuditLogText = function constructAuditLogText(_ref) {
  var action = _ref.action,
    performedBy = _ref.performedBy,
    _ref$emails = _ref.emails,
    emails = _ref$emails === void 0 ? [] : _ref$emails,
    firstName = _ref.firstName,
    lastName = _ref.lastName,
    organizationRole = _ref.organizationRole,
    email = _ref.email,
    _ref$changes = _ref.changes,
    changes = _ref$changes === void 0 ? {} : _ref$changes,
    status = _ref.status,
    message = _ref.message,
    errorMessage = _ref.errorMessage,
    addedPermissions = _ref.addedPermissions;
  switch (action) {
    case ACTIONS.INVITED_USERS:
      {
        if (status === "success" && isNotEmpty(emails)) {
          var emailList = emails.join(", ");
          return /*#__PURE__*/jsx(Trans, {
            additionalValues: {
              performedBy: performedBy,
              emailList: emailList
            },
            i18nKey: "neetoMolecules.auditLogs.text.invitedUsers"
          });
        }
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy,
            errorMessage: errorMessage
          },
          i18nKey: "neetoMolecules.auditLogs.text.invitedUsersFailed"
        });
      }
    case ACTIONS.USER_SIGNED_UP:
      {
        var name = [firstName, lastName].filter(Boolean).join(" ");
        var userIdentifier = name || organizationRole || email || "User";
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            userIdentifier: userIdentifier
          },
          i18nKey: "neetoMolecules.auditLogs.text.userSignedUp"
        });
      }
    case ACTIONS.UPDATED_USER:
      {
        var changedFields = formatChangedFields(changes);
        var affectedUser = email || "user";
        return /*#__PURE__*/jsx(Trans, {
          additionalComponents: {
            ChangedFields: /*#__PURE__*/jsx(Fragment, {
              children: changedFields
            })
          },
          additionalValues: {
            performedBy: performedBy,
            affectedUser: affectedUser,
            changedFields: changedFields
          },
          i18nKey: "neetoMolecules.auditLogs.text.updatedUser"
        });
      }
    case ACTIONS.BULK_UPDATE_USERS:
      {
        if (status === "success" && isNotEmpty(emails)) {
          var _emailList = emails.join(", ");
          return /*#__PURE__*/jsx(Trans, {
            additionalValues: {
              performedBy: performedBy,
              emailList: _emailList,
              message: message
            },
            i18nKey: "neetoMolecules.auditLogs.text.bulkUpdateUsers"
          });
        }
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy,
            errorMessage: errorMessage
          },
          i18nKey: "neetoMolecules.auditLogs.text.bulkUpdateUsersFailed"
        });
      }
    case ACTIONS.UPDATED_USER_PROFILE:
      {
        var _changedFields = formatChangedFields(changes);
        return /*#__PURE__*/jsx(Trans, {
          additionalComponents: {
            ChangedFields: /*#__PURE__*/jsx(Fragment, {
              children: _changedFields
            })
          },
          additionalValues: {
            performedBy: performedBy
          },
          i18nKey: "neetoMolecules.auditLogs.text.updatedUserProfile"
        });
      }
    case ACTIONS.CREATED_ROLE:
      {
        var roleName = organizationRole || "role";
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy,
            roleName: roleName
          },
          i18nKey: "neetoMolecules.auditLogs.text.createdRole"
        });
      }
    case ACTIONS.UPDATED_ROLE:
      {
        var _roleName = organizationRole || "role";
        var permissionsArray = values(addedPermissions).map(function (permission) {
          return humanize(permission.split(".")[1]);
        });
        var addedPermissionsText = permissionsArray.join(", ");
        return (
          /*#__PURE__*/
          // Disabling as we're using the same key for both singular and plural cases
          // eslint-disable-next-line @bigbinary/neeto/no-missing-localization
          jsx(Trans, {
            i18nKey: "neetoMolecules.auditLogs.text.updatedRole",
            additionalValues: {
              performedBy: performedBy,
              roleName: _roleName,
              addedPermissionsText: addedPermissionsText,
              count: permissionsArray.length
            }
          })
        );
      }
    case ACTIONS.CONNECTED_GOOGLE_CALENDER:
      {
        return /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.auditLogs.text.connectedGoogleCalender",
          additionalValues: {
            performedBy: performedBy,
            emailAddress: changes.emailAddress
          }
        });
      }
    case ACTIONS.DISCONNECTED_GOOGLE_CALENDER:
      {
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy
          },
          i18nKey: "neetoMolecules.auditLogs.text.disconnectedGoogleCalender"
        });
      }
    case ACTIONS.CONNECTED_STRIPE_ACCOUNT:
      {
        return /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.auditLogs.text.connectedStripeAccount",
          additionalValues: {
            performedBy: performedBy,
            stripeAccountId: changes.stripeAccountId
          }
        });
      }
    case ACTIONS.DISCONNECTED_STRIPE_ACCOUNT:
      {
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy
          },
          i18nKey: "neetoMolecules.auditLogs.text.disconnectedStripeAccount"
        });
      }
    case ACTIONS.CONNECTED_ZOOM_INTEGRATION:
      {
        return /*#__PURE__*/jsx(Trans, {
          i18nKey: "neetoMolecules.auditLogs.text.connectedZoomAccount",
          additionalValues: {
            performedBy: performedBy,
            zoomAccountId: changes.zoomAccountId
          }
        });
      }
    case ACTIONS.DISCONNECTED_ZOOM_INTEGRATION:
      {
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy
          },
          i18nKey: "neetoMolecules.auditLogs.text.disconnectedZoomAccount"
        });
      }
    case ACTIONS.CONNECTED_CUSTOM_DOMAIN:
      {
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy,
            hostname: changes.hostname
          },
          i18nKey: "neetoMolecules.auditLogs.text.connectedCustomDomain"
        });
      }
    case ACTIONS.DELETED_ROLE:
      {
        var _roleName2 = organizationRole || "role";
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy,
            roleName: _roleName2
          },
          i18nKey: "neetoMolecules.auditLogs.text.deletedRole"
        });
      }
    default:
      {
        return /*#__PURE__*/jsx(Trans, {
          additionalValues: {
            performedBy: performedBy
          },
          i18nKey: "neetoMolecules.auditLogs.text.performedAction"
        });
      }
  }
};

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 Card = function Card(_ref) {
  var auditLog = _ref.auditLog,
    index = _ref.index,
    totalCount = _ref.totalCount;
  var key = auditLog.key,
    metadata = auditLog.metadata,
    performer = auditLog.performer,
    updatedAt = auditLog.updatedAt;
  var action = transformAction(key);
  var performedBy = (performer === null || performer === void 0 ? void 0 : performer.name) || "";
  var performedAt = dateFormat.dateTime(updatedAt);
  var auditText = constructAuditLogText(_objectSpread$2({
    action: action,
    performedBy: performedBy
  }, metadata));
  var Icon = AUDIT_ICON_MAP[action];
  return /*#__PURE__*/jsxs("div", {
    className: classnames("align-items-center neeto-ui-border-gray-200 flex w-full gap-x-4 border-b border-l border-r p-3", {
      "rounded-t-md border-t": index === 0,
      "rounded-b-md": index === totalCount - 1
    }),
    children: [/*#__PURE__*/jsx("div", {
      className: "neeto-ui-rounded-full neeto-ui-bg-gray-100 flex size-10 flex-shrink-0 items-center justify-center",
      children: /*#__PURE__*/jsx(Icon, {
        className: "neeto-ui-text-gray-600 flex-shrink-0",
        size: 22
      })
    }), /*#__PURE__*/jsxs("div", {
      className: "flex flex-col gap-y-2",
      children: [/*#__PURE__*/jsx(Typography, {
        component: "span",
        lineHeight: "normal",
        style: "body2",
        children: auditText
      }), /*#__PURE__*/jsx(Typography, {
        className: "neeto-ui-text-gray-500 m-0",
        style: "body3",
        children: performedAt
      })]
    })]
  });
};

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 _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,
        pageSize: AUDIT_LOGS_PAGE_SIZE
      }
    }),
    _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;
  if (isLoading || isFetching) {
    return /*#__PURE__*/jsx("div", {
      className: "flex h-full w-full items-center justify-center",
      children: /*#__PURE__*/jsx(Spinner, {})
    });
  }
  return /*#__PURE__*/jsxs(Container, {
    className: "relative",
    children: [/*#__PURE__*/jsx(Header, _objectSpread({
      title: t("neetoMolecules.auditLogs.title")
    }, headerProps)), isPresent(auditLogs) ? /*#__PURE__*/jsx("div", {
      className: "w-full",
      children: auditLogs.map(function (auditLog, index) {
        return /*#__PURE__*/createElement(Card, {
          auditLog: auditLog,
          index: index,
          key: auditLog.id,
          totalCount: auditLogs.length
        });
      })
    }) : /*#__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(Pagination, {
      className: "neeto-ui-bg-white fixed bottom-5 right-6",
      count: totalCount,
      pageNo: parseInt(page),
      pageSize: AUDIT_LOGS_PAGE_SIZE
    })]
  });
};

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