import React, { forwardRef, useLayoutEffect, useRef } from "react";
import { createEvent } from "../../../../utils";
import { useForkRef } from "../../../../hooks";
import { SelectHidden } from "./SelectNative.styles";
export const SelectNative = /*#__PURE__*/ forwardRef(({ name, multiselect, items, value, handleChange, outerOnChange }, ref)=>{
    const values = Array.isArray(value) ? value : [
        value
    ].filter(Boolean);
    const selectRef = useRef(null);
    const forkRef = useForkRef(selectRef, ref);
    const options = Array.from(new Set([
        ...items.keys(),
        ...values
    ]));
    useLayoutEffect(()=>{
        if (selectRef.current && !multiselect) {
            const valueInit = selectRef.current.value;
            if (valueInit) {
                handleChange(valueInit, null);
            }
        }
        if (selectRef.current && multiselect) {
            const valuesInit = Array.from(selectRef.current.selectedOptions).map((v)=>v.value);
            if (valuesInit.length !== 0) {
                handleChange(valuesInit, null);
            }
        }
    }, []);
    useLayoutEffect(()=>{
        const event = createEvent(selectRef);
        if (event && outerOnChange) {
            outerOnChange(event);
        }
    }, [
        value,
        outerOnChange
    ]);
    return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(SelectHidden, {
        ref: forkRef,
        multiple: multiselect,
        name: name,
        hidden: true,
        value: multiselect ? values : values[0] ?? ''
    }, /*#__PURE__*/ React.createElement("option", {
        value: ""
    }, " "), options.map((option)=>/*#__PURE__*/ React.createElement("option", {
            key: option,
            value: option
        }, option))));
});
