import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState } from "react";
import { GetSvgIcon } from "..";
import TextDropdownItem from "./TextDropdownItem";
import "./style.scss";
const TextDropdown = ({ items, initialValue, initialSvg, onChange, }) => {
    const [extend, setExtend] = useState(false);
    const [selectedItem, setSelectedItem] = useState();
    const elementRef = useRef(null);
    const handleToggleExtend = () => {
        setExtend((prev) => !prev);
    };
    const handleItem = (e) => {
        console.log("E: ", e);
        setSelectedItem(e);
        setExtend(false);
    };
    const currentlySelectedItem = useMemo(() => selectedItem
        ? selectedItem
        : {
            itemName: initialValue,
            svgIcon: initialSvg,
        }, [selectedItem, initialValue, initialSvg]);
    const onItemClick = (itemName, svgIcon) => {
        handleItem({
            itemName,
            svgIcon,
        });
        onChange({
            itemName,
            svgIcon,
        });
    };
    // Add an event listener to the document to detect clicks outside the element
    useEffect(() => {
        function handleClickOutside(event) {
            if (elementRef.current &&
                !elementRef.current.contains(event.target) &&
                !elementRef.current.parentElement?.contains(event.target)) {
                handleToggleExtend();
            }
        }
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, []);
    return (_jsx("div", { children: _jsxs("div", { className: "TextDropdown-Wrapper", children: [_jsxs("div", { className: "TextDropdown-barContainer", onClick: handleToggleExtend, children: [_jsxs("div", { className: `TextDropdown-selectedTextContainer ${currentlySelectedItem.svgIcon}-icon`, children: [currentlySelectedItem.svgIcon && (_jsx(GetSvgIcon, { iconType: currentlySelectedItem.svgIcon, iconSize: "16" })), _jsx("span", { className: "TextDropdown-selectedText", children: currentlySelectedItem.itemName ?? "" })] }), _jsx("span", { className: "TextDropdown-dropdownSvg", children: _jsx(GetSvgIcon, { iconType: `${extend ? "cheveronUp" : "cheveronDown"}` }) })] }), extend && (_jsx("div", { className: "TextDropdown-dropdownBody", ref: elementRef, children: items.map((ele, idx) => {
                        return (_jsx(TextDropdownItem, { itemName: ele.itemName, svgIcon: ele.svgIcon, hasBorder: idx == items.length - 1, onClick: onItemClick }, ele.itemName + idx));
                    }) }))] }) }));
};
export default TextDropdown;
