"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.FilterForm = FilterForm;
exports.LabelFilterDropdown = void 0;

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

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

var _hi = require("react-icons/hi");

var _solid = require("@heroicons/react/solid");

var _LayoutDropdown = require("../../Dropdown/LayoutDropdown");

var _GroupByDropdown = require("../../Dropdown/GroupByDropdown");

var _TabByDropdown = require("../../Dropdown/TabByDropdown");

var _PivotByDropdown = require("../../Dropdown/PivotByDropdown");

var _PivotLabelDropdown = require("../../Dropdown/PivotLabelDropdown");

var _PivotCellTypeDropdown = require("../../Dropdown/PivotCellTypeDropdown");

var _Select = require("../../Select");

var _TimeRange = require("../../Dropdown/TimeRange");

var _Toggle = require("../../Toggle");

var _state = require("../state");

var _url = require("../url");

var _TristateToggle = require("../../TristateToggle");

var _DropdownMenu = require("../../DropdownMenu");

var _labels = require("../labels");

var _utils = require("../CanaryPopup/utils");

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

var _excluded = ["ref"],
    _excluded2 = ["ref"],
    _excluded3 = ["className", "children"],
    _excluded4 = ["children", "conciseLimit"],
    _excluded5 = ["labels", "onChange", "loadFromURL", "name"];

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 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; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

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 FilterForm(_ref) {
  var labels = _ref.labels,
      checks = _ref.checks,
      filterLabels = _ref.filterLabels,
      history = _ref.history,
      hideLabelFilters = _ref.hideLabelFilters,
      hideTimeRange = _ref.hideTimeRange,
      className = _ref.className,
      controlsContainerClassName = _ref.controlsContainerClassName,
      controlsControllerClassName = _ref.controlsControllerClassName,
      filtersContainerClassName = _ref.filtersContainerClassName,
      healthFilterClassName = _ref.healthFilterClassName,
      labelFilterClassName = _ref.labelFilterClassName,
      _ref$onServerSideFilt = _ref.onServerSideFilterChange,
      onServerSideFilterChange = _ref$onServerSideFilt === void 0 ? null : _ref$onServerSideFilt;
  var searchParams = window.location.search;

  var _initialiseFormState = (0, _state.initialiseFormState)((0, _state.getDefaultForm)(labels), searchParams),
      formState = _initialiseFormState.formState,
      fullState = _initialiseFormState.fullState;

  var _useForm = (0, _reactHookForm.useForm)({
    defaultValues: formState
  }),
      control = _useForm.control,
      watch = _useForm.watch,
      reset = _useForm.reset,
      getValues = _useForm.getValues,
      setValue = _useForm.setValue;

  (0, _react.useEffect)(function () {
    var encoded = (0, _url.encodeObjectToUrlSearchParams)(fullState);

    if (window.location.search !== "?".concat(encoded)) {
      history.push("".concat(window.location.pathname, "?").concat(encoded));
      reset(formState);
    }
  }, [formState, fullState, labels, history, reset]); // only trigger filter change on 2nd render and onwards

  var firstUpdate = (0, _react.useRef)(true);
  (0, _react.useEffect)(function () {
    if (firstUpdate.current) {
      firstUpdate.current = false;
    } else if (onServerSideFilterChange != null) {
      onServerSideFilterChange();
    }
  }, [formState.timeRange, onServerSideFilterChange]);
  var watchLayout = watch("layout");
  var watchPivotBy = watch("pivotBy");
  (0, _react.useEffect)(function () {
    var watchAll = watch(function (data) {
      var searchParams = window.location.search;

      var _updateFormState = (0, _state.updateFormState)(data, searchParams, labels),
          formState = _updateFormState.formState;

      var encoded = (0, _url.encodeObjectToUrlSearchParams)(formState);

      if (window.location.search !== "?".concat(encoded)) {
        // See https://github.com/remix-run/history/blob/main/docs/getting-started.md
        history.push("".concat(window.location.pathname, "?").concat(encoded));
      }
    });
    return function () {
      watchAll.unsubscribe();
    };
  });

  var _separateLabelsByBool = (0, _labels.separateLabelsByBooleanType)(Object.values(filterLabels)),
      _separateLabelsByBool2 = _slicedToArray(_separateLabelsByBool, 2),
      booleanLabels = _separateLabelsByBool2[0],
      nonBooleanLabels = _separateLabelsByBool2[1];

  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("form", {
    className: "relative ".concat(className),
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SectionTitle, {
      children: "Controls"
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: controlsContainerClassName,
      children: [!hideTimeRange && /*#__PURE__*/(0, _jsxRuntime.jsx)(_TimeRange.TimeRange, {
        control: control,
        name: "timeRange",
        className: controlsControllerClassName,
        label: "Time Range"
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_LayoutDropdown.LayoutDropdown, {
        control: control,
        name: "layout",
        className: controlsControllerClassName,
        label: "Layout"
      }), watchLayout === "table" && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_GroupByDropdown.GroupByDropdown, {
          name: "groupBy",
          control: control,
          className: controlsControllerClassName,
          label: "Group By",
          checks: checks
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_PivotByDropdown.PivotByDropdown, {
          name: "pivotBy",
          control: control,
          className: controlsControllerClassName,
          label: "Pivot By",
          checks: checks
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_TabByDropdown.TabByDropdown, {
        name: "tabBy",
        control: control,
        className: controlsControllerClassName,
        label: "Tab By",
        checks: checks
      })]
    }), !(watchPivotBy == null || watchPivotBy === "none") && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SectionTitle, {
        children: "Pivot Settings"
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: controlsContainerClassName,
        children: [watchPivotBy !== "none" && /*#__PURE__*/(0, _jsxRuntime.jsx)(_PivotCellTypeDropdown.PivotCellTypeDropdown, {
          name: "pivotCellType",
          control: control,
          className: controlsControllerClassName,
          label: "Cell Type",
          checks: checks
        }), watchPivotBy === "labels" && /*#__PURE__*/(0, _jsxRuntime.jsx)(_PivotLabelDropdown.PivotLabelDropdown, {
          name: "pivotLabel",
          control: control,
          className: controlsControllerClassName,
          label: "Pivot Label",
          checks: checks
        })]
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: filtersContainerClassName,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: healthFilterClassName,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SectionTitle, {
          children: "Filter By Health"
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHookForm.Controller, {
          name: "hidePassing",
          control: control,
          render: function render(_ref2) {
            var _ref2$field = _ref2.field,
                ref = _ref2$field.ref,
                rest = _objectWithoutProperties(_ref2$field, _excluded);

            return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Toggle.Toggle, _objectSpread({
              label: "Hide Passing"
            }, rest));
          }
        }, "hidePassing")]
      }), !hideLabelFilters && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: labelFilterClassName,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(SectionTitle, {
          children: "Filter By Label"
        }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
          className: "flex w-full",
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: filtersContainerClassName,
            style: {
              zIndex: 5,
              maxWidth: "300px"
            },
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(LabelFilterDropdown, {
              name: "labelFilter",
              labels: nonBooleanLabels,
              onChange: function onChange(selected, all) {
                // get current label state
                var newState = getValues("labels"); // initialize all nonBooleanLabels with 0s

                all.forEach(function (label) {
                  newState = (0, _utils.setDeepWithString)(label.value, 0, newState);
                }); // alter selected labels with 1s

                selected.forEach(function (label) {
                  newState = (0, _utils.setDeepWithString)(label.value, 1, newState);
                }); // set form

                setValue("labels", newState);
              }
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: filtersContainerClassName,
            style: {
              zIndex: "5"
            },
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_DropdownMenu.DropdownMenu, {
              buttonClass: "w-full",
              buttonElement: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                className: "border border-gray-300 w-full flex items-center justify-between px-2 py-2",
                style: {
                  height: "38px",
                  borderRadius: "4px"
                },
                children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                  className: "text-sm text-gray-500",
                  children: "Boolean labels"
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_solid.ChevronDownIcon, {
                  style: {
                    height: "20px",
                    color: "#8f8f8f",
                    marginLeft: "12px"
                  }
                })]
              }),
              content: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
                className: "px-4 py-2",
                children: booleanLabels.filter(function (o) {
                  return o && o !== undefined;
                }).map(function (label) {
                  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactHookForm.Controller, {
                    name: "labels.".concat(label.id),
                    control: control,
                    render: function render(_ref3) {
                      var _ref3$field = _ref3.field,
                          ref = _ref3$field.ref,
                          rest = _objectWithoutProperties(_ref3$field, _excluded2);

                      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_TristateToggle.TristateToggle, _objectSpread({
                        className: "mb-2",
                        label: label
                      }, rest), label.key);
                    }
                  }, label.id);
                })
              })
            })
          })]
        })]
      })]
    })]
  });
}

var SectionTitle = function SectionTitle(_ref4) {
  var className = _ref4.className,
      children = _ref4.children,
      props = _objectWithoutProperties(_ref4, _excluded3);

  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", _objectSpread(_objectSpread({
    className: "uppercase font-semibold text-sm mb-3 text-indigo-700 ".concat(className)
  }, props), {}, {
    children: children
  }));
};

var Option = function Option(props) {
  var isSelected = props.isSelected,
      children = props.children;
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Select.components.Option, _objectSpread(_objectSpread({}, props), {}, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "flex justify-between",
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        children: children
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: "ml-2",
        children: isSelected && /*#__PURE__*/(0, _jsxRuntime.jsx)(_hi.HiCheck, {
          className: "h-5 w-5"
        })
      })]
    })
  }));
};

var ConciseLabelsValueContainer = function ConciseLabelsValueContainer(_ref5) {
  var children = _ref5.children,
      _ref5$conciseLimit = _ref5.conciseLimit,
      conciseLimit = _ref5$conciseLimit === void 0 ? 4 : _ref5$conciseLimit,
      props = _objectWithoutProperties(_ref5, _excluded4);

  var currentValues = props.getValue();
  var toBeRendered = children;

  if (currentValues.some(function (val) {
    var _props$selectProps$al;

    return val.value === ((_props$selectProps$al = props.selectProps.allOption) === null || _props$selectProps$al === void 0 ? void 0 : _props$selectProps$al.value);
  })) {
    toBeRendered = _react.default.Children.toArray(children).filter(function (c) {
      var _props$selectProps$al2;

      return !c.props.data || c.props.data.value !== ((_props$selectProps$al2 = props.selectProps.allOption) === null || _props$selectProps$al2 === void 0 ? void 0 : _props$selectProps$al2.value);
    });
  }

  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Select.components.ValueContainer, _objectSpread(_objectSpread({}, props), {}, {
    children: currentValues.length < conciseLimit ? toBeRendered : /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "text-md text-gray-500",
      children: ["including ", currentValues.length === props.options.length && "all ", /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: "text-sm font-semibold",
        children: currentValues.length === props.options.length ? currentValues.length - 1 : currentValues.length
      }), " ", "labels"]
    })
  }));
};

var LabelFilterDropdown = function LabelFilterDropdown(_ref6) {
  var labels = _ref6.labels,
      onChange = _ref6.onChange,
      loadFromURL = _ref6.loadFromURL,
      name = _ref6.name,
      rest = _objectWithoutProperties(_ref6, _excluded5);

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

  var _useState3 = (0, _react.useState)([]),
      _useState4 = _slicedToArray(_useState3, 2),
      options = _useState4[0],
      setOptions = _useState4[1];

  var _useState5 = (0, _react.useState)(true),
      _useState6 = _slicedToArray(_useState5, 2),
      isInitialLoad = _useState6[0],
      setIsInitialLoad = _useState6[1];

  (0, _react.useEffect)(function () {
    var newOptions = labels.map(function (label) {
      return {
        value: label.id,
        label: label.value
      };
    });
    setOptions(newOptions);
  }, [labels]);
  (0, _react.useEffect)(function () {
    onChange(selected, options); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected]); // get initial selected labels from URL params on first load

  (0, _react.useEffect)(function () {
    if (loadFromURL && isInitialLoad && (labels === null || labels === void 0 ? void 0 : labels.length) > 0) {
      var _decodeUrlSearchParam = (0, _url.decodeUrlSearchParams)(window.location.search),
          urlLabelState = _decodeUrlSearchParam.labels;

      var initialSelected = Object.entries(urlLabelState).reduce(function (acc, _ref7) {
        var _ref8 = _slicedToArray(_ref7, 2),
            labelKey = _ref8[0],
            v = _ref8[1];

        if (v === 1 && labels.findIndex(function (o) {
          return o.id === labelKey;
        }) > -1) {
          var _labels$find;

          acc.push({
            value: labelKey,
            label: ((_labels$find = labels.find(function (o) {
              return o.id === labelKey;
            })) === null || _labels$find === void 0 ? void 0 : _labels$find.value) || labelKey
          });
        }

        return acc;
      }, []);
      setSelected(initialSelected);
      setIsInitialLoad(false);
    } // eslint-disable-next-line react-hooks/exhaustive-deps

  }, [isInitialLoad, labels]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_Select.Select, _objectSpread({
    name: name,
    styles: {
      control: function control(styles) {
        return _objectSpread(_objectSpread({}, styles), {}, {
          minWidth: "200px"
        });
      },
      menu: function menu(styles) {
        return _objectSpread(_objectSpread({}, styles), {}, {
          zIndex: 5
        });
      },
      option: function option(styles) {
        return _objectSpread(_objectSpread({}, styles), {}, {
          overflowX: "hidden",
          overflowWrap: "anywhere",
          fontSize: "12px"
        });
      },
      valueContainer: function valueContainer(styles) {
        return _objectSpread(_objectSpread({}, styles), {}, {
          flexWrap: "nowrap",
          fontSize: "14px"
        });
      }
    },
    options: options,
    value: selected,
    isMulti: true,
    allowSelectAll: true,
    hideSelectedOptions: false,
    components: {
      Option: Option
    },
    onChange: setSelected,
    customValueContainer: ConciseLabelsValueContainer
  }, rest));
};

exports.LabelFilterDropdown = LabelFilterDropdown;