import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef, useState } from 'react';
import { GetSvgIcon } from '..';
import clsx from 'clsx';
import styles from './style.module.scss';
const DropDownForm = ({ items, onSelect, }) => {
    const [extend, setExtend] = useState(false);
    const [selectedItem, setSelectedItem] = useState(items[0] || "");
    const elementRef = useRef(null);
    const handleArrow = () => {
        setExtend(prev => !prev);
    };
    const handleItem = (e) => {
        setSelectedItem(e);
        onSelect(e);
        setExtend(false);
    };
    // 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)) {
                handleArrow();
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);
    const getItemClasses = (index) => {
        return clsx(styles.dropdownItem, {
            [styles.itemFirst]: index === 0,
            [styles.itemLast]: index === items.length - 1
        });
    };
    return (_jsxs("div", { className: styles.dropdownContainer, children: [_jsxs("button", { type: 'button', className: styles.dropdownTrigger, onClick: handleArrow, children: [_jsxs("span", { className: styles.dropdownLabel, children: [" ", selectedItem, " "] }), _jsx("span", { className: styles.dropdownIcon, children: _jsx(GetSvgIcon, { iconType: `${extend ? 'cheveronUp' : 'cheveronDown'}`, iconSize: '18' }) })] }), extend &&
                _jsx("div", { className: styles.dropdownContent, ref: elementRef, children: items.map((ele, idx) => (_jsx("div", { className: getItemClasses(idx), onClick: () => handleItem(ele), children: ele }, ele + idx))) })] }));
};
export default DropDownForm;
