import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import cx from "classnames";
import { useEffect, useRef, useState } from "react";
import DropdownList from "../DropdownList";
import Icon from "../Icon";
import "./styles.scss";
export const DropdownFilterSizes = ["large", "medium", "small"];
export default function FilterDropdown({ text, list, selected = [], setSelected, className, disabled = false, active = false, size = "large", right = false, }) {
    const [show, setShow] = useState(false);
    const [hasSelected, setHasSelected] = useState(false);
    const [controlList, setControlList] = useState([]);
    const containerRef = useRef(null);
    const getClassNames = cx("ds-dropdown-filter", className, size, {
        active: !disabled && active,
        selected: !disabled && hasSelected,
        disabled: disabled,
    });
    const load = () => {
        setControlList(list.map((item) => ({
            ...item,
            icon: selected.some((s) => s.value === item.value)
                ? "check_box"
                : "check_box_outline_blank",
        })));
        setHasSelected(selected.length !== 0);
    };
    const handleSelect = (item) => {
        const items = selected.some((s) => s.value === item.value)
            ? selected.filter((s) => s.value !== item.value)
            : [...selected, item];
        setSelected && setSelected(items);
        setHasSelected(items.length !== 0);
    };
    useEffect(() => {
        load();
    }, [selected]);
    useEffect(() => {
        function handleClickOutside(event) {
            if (containerRef.current &&
                !containerRef.current.contains(event.target)) {
                setShow(false);
            }
        }
        if (show) {
            document.addEventListener("mousedown", handleClickOutside);
        }
        else {
            document.removeEventListener("mousedown", handleClickOutside);
        }
        // Cleanup on unmount or when show changes
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [show]);
    return (_jsxs("div", { className: "ds-filter-container", onClick: () => setShow(!show), ref: containerRef, children: [_jsxs("div", { className: getClassNames, children: [_jsx("button", { type: "button", disabled: disabled, className: "main-button", children: _jsx("span", { children: text }) }), _jsx("button", { type: "button", disabled: disabled, className: "icon-button", children: _jsx(Icon, { name: "arrow_drop_down", size: "x-small" }) })] }), show && (_jsx(DropdownList, { list: controlList, onSelect: handleSelect, right: right }))] }));
}
