"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.IncidentListPage = IncidentListPage;
exports.tempTypes = void 0;

var _react = _interopRequireWildcard(require("react"));

var _reactRouterDom = require("react-router-dom");

var _ai = require("react-icons/ai/");

var _reactHookForm = require("react-hook-form");

var _lodash = require("lodash");

var _incident = require("../../api/services/incident");

var _IncidentCreate = require("../../components/Incidents/IncidentCreate");

var _IncidentList = require("../../components/Incidents/IncidentList");

var _Modal = require("../../components/Modal");

var _Layout = require("../../components/Layout");

var _Loading = require("../../components/Loading");

var _Dropdown = require("../../components/Dropdown");

var _MultiSelectDropdown = require("../../components/MultiSelectDropdown");

var _data = require("../../components/Incidents/data");

var _users = require("../../api/services/users");

var _jsxRuntime = require("react/jsx-runtime");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var tempTypes = [{
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ai.AiOutlineQuestion, {}),
  description: "All",
  value: "all"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ai.AiOutlineQuestion, {}),
  description: "Value 1",
  value: "value1"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ai.AiOutlineQuestion, {}),
  description: "Value 2",
  value: "value2"
}, {
  icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ai.AiOutlineQuestion, {}),
  description: "Value 3",
  value: "value3"
}];
exports.tempTypes = tempTypes;
var defaultSelections = {
  all: {
    description: "All",
    value: "all",
    order: 0
  }
}; // to be removed after integrating with API

var mockLabels = [{
  value: "chocolate",
  label: "Chocolate"
}, {
  value: "strawberry",
  label: "Strawberry"
}, {
  value: "vanilla",
  label: "Vanilla"
}, {
  value: "banana",
  label: "Banana"
}, {
  value: "grape",
  label: "Grape"
}, {
  value: "pear",
  label: "Pear"
}];
var labelDropdownStyles = {
  valueContainer: function valueContainer(provided) {
    return _objectSpread({}, provided);
  },
  option: function option(provided) {
    return _objectSpread(_objectSpread({}, provided), {}, {
      fontSize: "14px"
    });
  },
  multiValueLabel: function multiValueLabel(provided) {
    return _objectSpread(_objectSpread({}, provided), {}, {
      fontSize: "12px"
    });
  },
  container: function container(provided) {
    return _objectSpread(_objectSpread({}, provided), {}, {
      minWidth: "300px"
    });
  }
};

function IncidentListPage() {
  var _useSearchParams = (0, _reactRouterDom.useSearchParams)(),
      _useSearchParams2 = _slicedToArray(_useSearchParams, 2),
      searchParams = _useSearchParams2[0],
      setSearchParams = _useSearchParams2[1];

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: {
      severity: searchParams.get("severity") || Object.values(defaultSelections)[0].value,
      status: searchParams.get("status") || Object.values(defaultSelections)[0].value,
      owner: searchParams.get("owner") || Object.values(defaultSelections)[0].value
    }
  }),
      control = _useForm.control,
      getValues = _useForm.getValues,
      watch = _useForm.watch;

  var _useState = (0, _react.useState)([]),
      _useState2 = _slicedToArray(_useState, 2),
      selectedLabels = _useState2[0],
      setSelectedLabels = _useState2[1];

  var navigate = (0, _reactRouterDom.useNavigate)();

  var _useState3 = (0, _react.useState)(true),
      _useState4 = _slicedToArray(_useState3, 2),
      isLoading = _useState4[0],
      setIsLoading = _useState4[1];

  var _useState5 = (0, _react.useState)([]),
      _useState6 = _slicedToArray(_useState5, 2),
      incidents = _useState6[0],
      setIncidents = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = _slicedToArray(_useState7, 2),
      incidentModalIsOpen = _useState8[0],
      setIncidentModalIsOpen = _useState8[1];

  var _useState9 = (0, _react.useState)([]),
      _useState10 = _slicedToArray(_useState9, 2),
      ownerSelections = _useState10[0],
      setOwnerSelections = _useState10[1];

  var watchSeverity = watch("severity");
  var watchStatus = watch("status");
  var watchOwner = watch("owner");
  (0, _react.useEffect)(function () {
    (0, _users.getPersons)().then(function (res) {
      var owners = res.data.reduce(function (acc, current) {
        acc[current.id] = _objectSpread(_objectSpread({}, current), {}, {
          value: current.id,
          description: current.name
        });
        return acc;
      }, {});
      setOwnerSelections(owners);
    });
  }, []);
  var loadIncidents = (0, _react.useRef)((0, _lodash.debounce)(function (severity, status, owner // labels
  ) {
    // TODO: integrate labels
    setIsLoading(true);
    var params = {
      severity: severity,
      status: status,
      created_by: owner
    };
    Object.entries(params).forEach(function (_ref) {
      var _ref2 = _slicedToArray(_ref, 2),
          key = _ref2[0],
          value = _ref2[1];

      if (value === "all") {
        delete params[key];
      } else {
        params[key] = "eq.".concat(value);
      }
    });
    (0, _incident.getIncidentsWithParams)(params).then(function (res) {
      setIncidents(res.data);
      setIsLoading(false);
    });
  }, 100)).current;
  (0, _react.useEffect)(function () {
    loadIncidents();
  }, [loadIncidents]);

  var saveQueryParams = function saveQueryParams() {
    var labelsArray = selectedLabels.map(function (o) {
      return o.value;
    });
    var encodedLabels = encodeURIComponent(JSON.stringify(labelsArray));

    var paramsList = _objectSpread(_objectSpread({}, getValues()), {}, {
      labels: encodedLabels
    });

    var params = {};
    Object.entries(paramsList).forEach(function (_ref3) {
      var _ref4 = _slicedToArray(_ref3, 2),
          key = _ref4[0],
          value = _ref4[1];

      if (value) {
        params[key] = value;
      }
    });
    setSearchParams(params);
  };

  (0, _react.useEffect)(function () {
    saveQueryParams();
    loadIncidents(watchSeverity, watchStatus, watchOwner, selectedLabels); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [watchSeverity, watchStatus, watchOwner, selectedLabels]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_Layout.SearchLayout, {
      title: /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex items-center flex-shrink-0",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
            className: "text-xl font-semibold mr-4 whitespace-nowrap",
            children: ["Incidents /", " "]
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "flex",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
              type: "button",
              className: "",
              onClick: function onClick() {
                return setIncidentModalIsOpen(true);
              },
              children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_ai.AiFillPlusCircle, {
                size: 36,
                color: "#326CE5"
              })
            })
          })]
        })
      }),
      onRefresh: loadIncidents,
      extra: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "flex",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex items-center mr-4",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-3 text-gray-500 text-sm",
            children: "Severity"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
            control: control,
            name: "severity",
            className: "w-36 mr-2 flex-shrink-0",
            items: _objectSpread(_objectSpread({}, defaultSelections), _data.severityItems)
          })]
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex items-center mr-4",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-3 text-gray-500 text-sm",
            children: "Status"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
            control: control,
            name: "status",
            className: "w-36 mr-2 flex-shrink-0",
            items: _objectSpread(_objectSpread({}, defaultSelections), _data.statusItems)
          })]
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex items-center mr-4",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-3 text-gray-500 text-sm",
            children: "Owner"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Dropdown.Dropdown, {
            control: control,
            name: "owner",
            className: "w-36 mr-2 flex-shrink-0",
            items: _objectSpread(_objectSpread({}, defaultSelections), ownerSelections)
          })]
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex items-center",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "mr-3 text-gray-500 text-sm",
            children: "Labels"
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_MultiSelectDropdown.MultiSelectDropdown, {
            styles: labelDropdownStyles,
            className: "w-full",
            options: mockLabels // TODO: change this to actual labels fetched from API
            ,
            onChange: function onChange(labels) {
              return setSelectedLabels(labels);
            },
            value: selectedLabels
          })]
        })]
      }),
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "leading-1.21rel",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
          className: "flex-none flex-wrap space-x-2 space-y-2",
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: "max-w-screen-xl mx-auto flex flex-col justify-center",
            children: !isLoading ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_IncidentList.IncidentList, {
              list: incidents || []
            }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Loading.Loading, {
              text: "fetching incidents"
            })
          })
        })
      })
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_Modal.Modal, {
      open: incidentModalIsOpen,
      onClose: function onClose() {
        return setIncidentModalIsOpen(false);
      },
      size: "small",
      title: "Create New Incident",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_IncidentCreate.IncidentCreate, {
        callback: function callback(response) {
          navigate("/incidents/".concat(response.id), {
            replace: true
          });
        }
      })
    })]
  });
}