"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InputTags = void 0;
var react_1 = __importStar(require("react"));
var useDidUpdateEffect_1 = require("@devesharp/react-hooks/lib/useDidUpdateEffect");
var useEventListener_1 = require("@devesharp/react-hooks/lib/useEventListener");
var faCheck_1 = require("@fortawesome/free-solid-svg-icons/faCheck");
var react_fontawesome_1 = require("@fortawesome/react-fontawesome");
var classnames_1 = __importDefault(require("classnames"));
var isEqual_1 = __importDefault(require("lodash/isEqual"));
var use_deep_compare_effect_1 = require("use-deep-compare-effect");
var use_immer_1 = require("use-immer");
var AutocompletePure_1 = require("../AutocompletePure");
var CloseBtn_1 = require("../CloseBtn");
var Input_1 = require("../Input");
var UnformInput_1 = require("../UnformInput");
var S = __importStar(require("./InputTags.style"));
var InputAutoComplete = react_1.default.forwardRef(function InputAutoComplete(_a, ref) {
    var _handleInputChange = _a._handleInputChange, _openAutoComplete = _a._openAutoComplete, _closeAutoComplete = _a._closeAutoComplete, _loading = _a._loading, _onChange = _a.onChange, name = _a.name, title = _a.title, _b = _a.cleanAfterSelect, cleanAfterSelect = _b === void 0 ? false : _b, tagsDefault = _a.tags, _c = _a.CustomTag, CustomTag = _c === void 0 ? Tag : _c, rest = __rest(_a, ["_handleInputChange", "_openAutoComplete", "_closeAutoComplete", "_loading", "onChange", "name", "title", "cleanAfterSelect", "tags", "CustomTag"]);
    var inputRef = (0, react_1.useRef)();
    var _d = (0, react_1.useState)(false), focus = _d[0], setFocus = _d[1];
    var _e = (0, react_1.useState)(''), error = _e[0], setError = _e[1];
    var _f = (0, use_immer_1.useImmer)([]), _tags = _f[0], setTags = _f[1];
    var tags = tagsDefault || _tags;
    (0, useDidUpdateEffect_1.useDidUpdateEffect)(function () {
        setTags(function (v) {
            if (!(0, isEqual_1.default)(tagsDefault, v))
                return tagsDefault;
        });
    }, [tagsDefault]);
    (0, use_deep_compare_effect_1.useDeepCompareEffectNoCheck)(function () {
        if (_onChange)
            _onChange(_tags);
    }, [_tags]);
    (0, react_1.useImperativeHandle)(ref, function () { return ({
        onSelect: function (item) {
            setTags(function (v) {
                if (v.find(function (tag) { return (0, isEqual_1.default)(tag.value, item.value); })) {
                    var tmp = __spreadArray([], v, true);
                    tmp.splice(v.findIndex(function (tag) { return (0, isEqual_1.default)(tag.value, item.value); }), 1);
                    return tmp;
                }
                return __spreadArray(__spreadArray([], v, true), [
                    {
                        name: item.name,
                        value: item.value,
                    },
                ], false);
            });
        },
    }); });
    function onInput(value) {
        _handleInputChange(value);
        if (rest.onInput)
            rest.onInput(value);
    }
    function onFocus(e) {
        _openAutoComplete();
        setFocus(true);
        if (rest.onFocus)
            rest.onFocus(e);
    }
    function onBlur(e) {
        setFocus(false);
        if (cleanAfterSelect)
            inputRef.current.value = '';
        if (rest.onBlur)
            rest.onBlur(e);
    }
    function onChange(v) {
        setTags(function () { return (Array.isArray(v) ? v : []); });
    }
    function onError(err) {
        setError(err);
    }
    function removeTag(tagValue) {
        setTags(function (v) {
            if (v.find(function (tag) { return (0, isEqual_1.default)(tag.value, tagValue.value); })) {
                var tmp = __spreadArray([], v, true);
                tmp.splice(v.findIndex(function (tag) { return (0, isEqual_1.default)(tag.value, tagValue.value); }), 1);
                return tmp;
            }
            return v;
        });
    }
    (0, useEventListener_1.useEventListener)('keydown.tab', function () {
        _closeAutoComplete();
    });
    return (react_1.default.createElement(react_1.default.Fragment, null,
        !!name && react_1.default.createElement(UnformInput_1.UnformInput, { name: name, onChange: onChange, value: tags, onError: onError }),
        title && react_1.default.createElement("div", { className: "input-title ".concat(focus && 'focus') }, title),
        react_1.default.createElement("div", { className: (0, classnames_1.default)(['input-border', 'autocomplete-border', focus && 'focus', error && 'has-error']) },
            !!tags.length && (react_1.default.createElement("span", { className: "tags" }, tags.map(function (tag, i) { return (react_1.default.createElement(CustomTag, { key: "tag-".concat(i, "-").concat(tag.name), tag: tag, index: i, removeTag: function () { return removeTag(tag); } })); }))),
            react_1.default.createElement(Input_1.Input, __assign({}, rest, { ref: inputRef, onInput: onInput, onFocus: onFocus, onBlur: onBlur, loading: _loading, "data-testid": "autocomplete--input" }))),
        error && (react_1.default.createElement("div", { className: "error-input", "data-testid": "input-error" }, error))));
});
function InputTags(props) {
    var _a = (0, react_1.useState)([]), _tags = _a[0], setTags = _a[1];
    var tags = props.tags || _tags;
    function onChange(_tags2) {
        setTags(_tags2);
        if (props.onChange)
            props.onChange(_tags2);
    }
    return (react_1.default.createElement(S.Container, null,
        react_1.default.createElement(AutocompletePure_1.AutocompletePure, __assign({}, props, { as: InputAutoComplete, onChange: onChange, renderRow: function (name, value, active) { return (react_1.default.createElement(RenderRow, { name: name, value: value, disabled: value.disabled, active: active, selected: !!tags.find(function (tag) { return (0, isEqual_1.default)(tag.value, value); }) })); }, persistOpenAutoCompleteItemsAfterSelect: true }))));
}
exports.InputTags = InputTags;
function Tag(_a) {
    var tag = _a.tag, index = _a.index, removeTag = _a.removeTag;
    return (react_1.default.createElement("div", { className: "tag", onClick: function () { return removeTag && removeTag(); }, "data-testid": "tag-".concat(index) },
        react_1.default.createElement("div", { className: "name" }, tag.name),
        react_1.default.createElement("div", { className: "close-btn-container" },
            react_1.default.createElement(CloseBtn_1.CloseBtn, { size: 10, color: "white" }))));
}
var RenderRow = react_1.default.memo(function RenderRow(_a) {
    var name = _a.name, value = _a.value, disabled = _a.disabled, selected = _a.selected, active = _a.active;
    return (react_1.default.createElement("div", { className: "item-row ".concat(active && 'active', " ").concat(disabled && 'disabled', " ").concat(selected && 'selected') },
        react_1.default.createElement("span", { className: "checkbox ".concat(selected && 'active') },
            react_1.default.createElement(react_fontawesome_1.FontAwesomeIcon, { icon: faCheck_1.faCheck })),
        name));
}, isEqual_1.default);
//# sourceMappingURL=InputTags.js.map